Ejemplo n.º 1
0
        public bool Configure()
        {
            try
            {
                // Make sure the root path exists
                if (!Engine.FileSystem.GetRootDirectory().Exists)
                {
                    throw new InvalidOperationException($"The root path {Engine.FileSystem.RootPath.FullPath} does not exist.");
                }

                // If we have a configuration file use it, otherwise configure with defaults
                IFile configFile = Engine.FileSystem.GetRootFile(_settings.ConfigFilePath);
                if (configFile.Exists)
                {
                    Trace.Information("Loading configuration from {0}", configFile.Path);
                    Configurator.OutputScriptPath = configFile.Path.ChangeExtension(".generated.cs");
                    Configurator.Configure(configFile.ReadAllText());
                }
                else
                {
                    Trace.Information("Could not find configuration file {0}, using default configuration", _settings.ConfigFilePath);
                    Configurator.Configure(GetDefaultConfigScript());
                }
            }
            catch (Exception ex)
            {
                Trace.Critical("Error while loading configuration: {0}", ex);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 2
0
        //public static void TransferTokenFrontTest(string FromAddress_Buyer, string ToAddress_Owner, string Amount)
        //{
        //    Task task = System.Threading.Tasks.Task.Run(async () => await (DoTransaction(FromAddress_Buyer, ToAddress_Owner, Amount)));
        //}

        public async static Task <CreateWalletModel> CreateUserWallet()
        {
            ITrace            telemetria   = new Trace();
            CreateWalletModel _walletModel = new CreateWalletModel();

            try
            {
                //Generate RandomPassword
                string _passphrase = Guid.NewGuid().ToString().Replace("-", "") + GetRandomNumber(1842).ToString();

                string _blobname = BlobManager.CreateUsrWalletBlobFile(_passphrase, ConfigurationManager.AppSettings["azure-storage-connectionstring"]);

                var web3           = new Nethereum.Web3.Web3(ConfigurationManager.AppSettings["BlockchainURL"]);
                var _walletAddress = await web3.Personal.NewAccount.SendRequestAsync(_passphrase);

                _walletModel = new CreateWalletModel()
                {
                    blobname = _blobname, walletaddress = _walletAddress
                };
            }
            catch (Exception e)
            {
                var messageException = telemetria.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name);
                telemetria.Critical(messageException);
            }

            return(_walletModel);
        }
Ejemplo n.º 3
0
        public static IDisposable Start(DirectoryPath path, int port, bool forceExtension)
        {
            IDisposable server;

            try
            {
                StartOptions options = new StartOptions("http://localhost:" + port);

                // Disable built-in owin tracing by using a null trace output
                // http://stackoverflow.com/questions/17948363/tracelistener-in-owin-self-hosting
                options.Settings.Add(typeof(ITraceOutputFactory).FullName, typeof(NullTraceOutputFactory).AssemblyQualifiedName);

                server = WebApp.Start(options, app =>
                {
                    Microsoft.Owin.FileSystems.IFileSystem outputFolder = new PhysicalFileSystem(path.FullPath);

                    // Disable caching
                    app.Use((c, t) =>
                    {
                        c.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
                        c.Response.Headers.Append("Pragma", "no-cache");
                        c.Response.Headers.Append("Expires", "0");
                        return(t());
                    });

                    // Support for extensionless URLs
                    if (!forceExtension)
                    {
                        app.UseExtensionlessUrls(new ExtensionlessUrlsOptions
                        {
                            FileSystem = outputFolder
                        });
                    }

                    // Serve up all static files
                    app.UseDefaultFiles(new DefaultFilesOptions
                    {
                        RequestPath      = PathString.Empty,
                        FileSystem       = outputFolder,
                        DefaultFileNames = new List <string> {
                            "index.html", "index.htm", "home.html", "home.htm", "default.html", "default.html"
                        }
                    });
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        RequestPath           = PathString.Empty,
                        FileSystem            = outputFolder,
                        ServeUnknownFileTypes = true
                    });
                });
            }
            catch (Exception ex)
            {
                Trace.Critical("Error while running preview server: {0}", ex.Message);
                return(null);
            }

            Trace.Information("Preview server listening on port {0} and serving from path {1}", port, path);
            return(server);
        }
Ejemplo n.º 4
0
        private bool Configure(Engine engine)
        {
            try
            {
                // If we have a configuration file use it, otherwise configure with defaults
                IFile configFile = engine.FileSystem.GetRootFile(_configFilePath);
                if (configFile.Exists)
                {
                    Trace.Information("Loading configuration from {0}", configFile.Path);
                    engine.Configure(configFile, _updatePackages, _outputScripts);
                }
                else
                {
                    Trace.Information("Could not find configuration file {0}, using default configuration", _configFilePath);
                    engine.Configure(GetDefaultConfigScript(), _updatePackages);
                }
            }
            catch (Exception ex)
            {
                Trace.Critical("Error while loading configuration: {0}", ex.Message);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Read the configuration from the file
        /// </summary>
        private void ReadConfiguration()
        {
            string  text    = null;
            JObject jConfig = null;

            try
            {
                text = File.ReadAllText(ConfigurationFileName);
            }
            catch (Exception e)
            {
                Trace.Critical($"Could not find config file. {e.Message}");
                Environment.FailFast("Could not find configuration.");
            }

            try
            {
                jConfig = JObject.Parse(text);
            }
            catch (Exception e)
            {
                Trace.Critical($"Configuration is invalid json. {e.Message}");
                Environment.FailFast("Configuration is invalid json.");
            }

            this.Queues = ((JArray)jConfig["queues"]).Select(q => new QueueConfigItem()
            {
                Name = q["name"].ToObject <string>()
            });
        }
Ejemplo n.º 6
0
        private static void Main(string[] args)
        {
            try
            {
                // Parsing arguments
                if (args.Length < 1 || !int.TryParse(args[0], out var num))
                {
                    ShowUsage();
                    return;
                }

                foreach (var arg in args.Skip(1))
                {
                    if (arg.ToLowerInvariant() == "-verbose")
                    {
                        TraceBuilder.SetLogFilter(e => true);
                    }
                }


                // Composition Root
                var app =
                    new Creator(
                        TraceBuilder.BuildTraceFor <Creator>());


                // Do the work
                app.MakeFiles(Directory.GetCurrentDirectory(), num);
            }
            catch (Exception e) // App entry point is one of the few places a Pokemon handler is OK
            {
                Trace.Critical(e);
                Environment.FailFast(e.Message, e);
            }
        }
Ejemplo n.º 7
0
        private static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;

            Trace.Critical(ex);
            Environment.FailFast(ex.Message, ex);
        }
Ejemplo n.º 8
0
 private EngineManager GetEngineManager()
 {
     try
     {
         return(new EngineManager(_preprocessor, _settings));
     }
     catch (Exception ex)
     {
         Trace.Critical("Error while instantiating engine: {0}", ex.Message);
         return(null);
     }
 }
Ejemplo n.º 9
0
        private static void UnhandledExceptionEvent(object sender, UnhandledExceptionEventArgs e)
        {
            // Exit with a error exit code
            Exception exception = e.ExceptionObject as Exception;

            if (exception != null)
            {
                Trace.Critical(exception.Message);
                Trace.Verbose(exception.ToString());
            }
            Environment.Exit((int)ExitCode.UnhandledError);
        }
Ejemplo n.º 10
0
 public static EngineManager Get(Preprocessor preprocessor, ConfigOptions configOptions)
 {
     try
     {
         return(new EngineManager(preprocessor, configOptions));
     }
     catch (Exception ex)
     {
         Trace.Critical("Error while instantiating engine: {0}", ex.Message);
         return(null);
     }
 }
Ejemplo n.º 11
0
        private Engine GetEngine()
        {
            try
            {
                Engine engine = new Engine();

                // Set verbose tracing
                if (_verbose)
                {
                    Trace.Level = System.Diagnostics.SourceLevels.Verbose;
                }

                // Set no cache if requested
                if (_noCache)
                {
                    engine.Settings.UseCache = false;
                }

                // Set folders
                engine.FileSystem.RootPath = _rootPath;
                if (_inputPaths != null && _inputPaths.Count > 0)
                {
                    // Clear existing default paths if new ones are set
                    // and reverse the inputs so the last one is first to match the semantics of multiple occurrence single options
                    engine.FileSystem.InputPaths.Clear();
                    engine.FileSystem.InputPaths.AddRange(_inputPaths.Reverse());
                }
                if (_outputPath != null)
                {
                    engine.FileSystem.OutputPath = _outputPath;
                }
                if (_noClean)
                {
                    engine.Settings.CleanOutputPath = false;
                }
                if (_globalMetadata != null)
                {
                    foreach (KeyValuePair <string, object> item in _globalMetadata)
                    {
                        engine.GlobalMetadata.Add(item);
                    }
                }

                engine.ApplicationInput = _stdin;

                return(engine);
            }
            catch (Exception ex)
            {
                Trace.Critical("Error while instantiating engine: {0}", ex.Message);
                return(null);
            }
        }
Ejemplo n.º 12
0
        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));
        }
Ejemplo n.º 13
0
        public bool Configure()
        {
            try
            {
                // make sure we clear out anything in the JavaScriptEngineSwitcher instance
                Engine.ResetJsEngines();

                // Make sure the root path exists
                if (!Engine.FileSystem.GetRootDirectory().Exists)
                {
                    throw new InvalidOperationException(
                              $"The root path {Engine.FileSystem.RootPath.FullPath} does not exist.");
                }

                // If we have a configuration file use it, otherwise configure with defaults
                IFile configFile = Engine.FileSystem.GetRootFile(_configOptions.ConfigFilePath);
                if (configFile.Exists)
                {
                    Trace.Information("Loading configuration from {0}", configFile.Path);
                    Configurator.OutputScriptPath = configFile.Path.ChangeExtension(".generated.cs");
                    Configurator.ConfigDllPath    = configFile.Path.ChangeExtension(".wyam.dll");
                    Configurator.ConfigHashPath   = configFile.Path.ChangeExtension(".wyam.hash");
                    Configurator.Configure(configFile.ReadAllText());
                }
                else
                {
                    Trace.Information("Could not find configuration file at {0}", _configOptions.ConfigFilePath);
                    Configurator.Configure(null);
                }
            }
            catch (ScriptCompilationException)
            {
                // Don't need to show exception message since it was already reported via trace
                Trace.Critical("Error while compiling configuration");
                return(false);
            }
            catch (Exception ex)
            {
                Trace.Critical("Error while loading configuration: {0}", ex);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 14
0
        public static Server Start(DirectoryPath path, int port, bool forceExtension, DirectoryPath virtualDirectory, bool liveReload)
        {
            Server server;

            try
            {
                server = new Server(path.FullPath, port, !forceExtension, virtualDirectory?.FullPath, liveReload, new TraceLoggerProvider());
                server.Start();
            }
            catch (Exception ex)
            {
                Trace.Critical($"Error while running preview server: {ex}");
                return(null);
            }

            Trace.Information($"Preview server listening on port {port} and serving from path {path}"
                              + (virtualDirectory == null ? string.Empty : $" with virtual directory {virtualDirectory.FullPath}")
                              + (liveReload ? " and LiveReload support" : string.Empty));
            return(server);
        }
Ejemplo n.º 15
0
    public static Server Start(DirectoryPath path, int port, bool forceExtension, DirectoryPath virtualDirectory, bool liveReload, IDictionary <string, string> contentTypes)
    {
        Server server;

        try
        {
            server = new Server(path.FullPath, port, !forceExtension, virtualDirectory?.FullPath, liveReload, contentTypes, Microsoft.Extensions.Logging.Abstractions.NullLoggerProvider.Instance);
            server.Start();
        }
        catch (Exception ex)
        {
            Trace.Critical($"Error while running preview server: {ex}");
            return(null);
        }

        string urlPath = server.VirtualDirectory == null ? string.Empty : server.VirtualDirectory;

        Trace.Information($"Preview server listening at http://localhost:{port}{urlPath} and serving from path {path}"
                          + (liveReload ? " with LiveReload support" : string.Empty));
        return(server);
    }
Ejemplo n.º 16
0
 public BaseManager(string endpointUrl, string primaryKey)
 {
     telemetria = new Trace();
     try
     {
         if (endpointUrl.Equals(string.Empty) || primaryKey.Equals(string.Empty))
         {
             Inicialization();
             context = new KindAdsV2DataAccess(this.endpointUrl, this.primaryKey);
         }
         else
         {
             context = new KindAdsV2DataAccess(endpointUrl, primaryKey);
         }
     }
     catch (Exception e)
     {
         var messageException = telemetria.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name);
         telemetria.Critical(messageException);
     }
 }
        public bool Configure()
        {
            try
            {
                // make sure we clear out anything in the JavaScriptEngineSwitcher instance
                Engine.ResetJsEngines();

                // Make sure the root path exists
                if (!Engine.FileSystem.GetRootDirectory().Exists)
                {
                    throw new InvalidOperationException(
                              $"The root path {Engine.FileSystem.RootPath.FullPath} does not exist.");
                }

                // If we have a configuration file use it, otherwise configure with defaults
                Trace.Information($"Loading configuration from {_configOptions.ConfigFilePath}");
                if (!Configurator.Configure(_configOptions.ConfigFilePath))
                {
                    Trace.Information($"Could not find configuration file at {_configOptions.ConfigFilePath}");
                    Configurator.Configure((string)null);
                }
            }
            catch (ScriptCompilationException)
            {
                // Don't need to show exception message since it was already reported via trace
                Trace.Critical("Error while compiling configuration");
                return(false);
            }
            catch (Exception ex)
            {
                Trace.Critical("Error while loading configuration: {0}", ex);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Executes the engine. This is the primary method that kicks off generation.
        /// </summary>
        public void Execute()
        {
            CheckDisposed();

            Trace.Information($"Using {JsEngineSwitcher.Instance.DefaultEngineName} as the JavaScript engine");

            // Make sure we've actually configured some pipelines
            if (_pipelines.Count == 0)
            {
                Trace.Error("No pipelines are configured. Please supply a configuration file, specify a recipe, or configure programmatically");
                return;
            }

            // Do a check for the same input/output path
            if (FileSystem.InputPaths.Any(x => x.Equals(FileSystem.OutputPath)))
            {
                Trace.Warning("The output path is also one of the input paths which can cause unexpected behavior and is usually not advised");
            }

            CleanTempPath();

            // Clean the output folder if requested
            if (Settings.Bool(Keys.CleanOutputPath))
            {
                CleanOutputPath();
            }

            try
            {
                System.Diagnostics.Stopwatch engineStopwatch = System.Diagnostics.Stopwatch.StartNew();
                using (Trace.WithIndent().Information("Executing {0} pipelines", _pipelines.Count))
                {
                    // Setup (clear the document collection and reset cache counters)
                    DocumentCollection.Clear();
                    ExecutionCacheManager.ResetEntryHits();

                    // Enumerate pipelines and execute each in order
                    Guid executionId = Guid.NewGuid();
                    int  c           = 1;
                    foreach (IPipeline pipeline in _pipelines.Pipelines)
                    {
                        string pipelineName = pipeline.Name;
                        System.Diagnostics.Stopwatch pipelineStopwatch = System.Diagnostics.Stopwatch.StartNew();
                        using (Trace.WithIndent().Information("Executing pipeline \"{0}\" ({1}/{2}) with {3} child module(s)", pipelineName, c, _pipelines.Count, pipeline.Count))
                        {
                            try
                            {
                                ((ExecutionPipeline)pipeline).Execute(this, executionId);
                                pipelineStopwatch.Stop();
                                Trace.Information(
                                    "Executed pipeline \"{0}\" ({1}/{2}) in {3} ms resulting in {4} output document(s)",
                                    pipelineName,
                                    c++,
                                    _pipelines.Count,
                                    pipelineStopwatch.ElapsedMilliseconds,
                                    DocumentCollection.FromPipeline(pipelineName).Count());
                            }
                            catch (Exception)
                            {
                                Trace.Error("Error while executing pipeline {0}", pipelineName);
                                throw;
                            }
                        }
                    }

                    // Clean up (clear unhit cache entries, dispose documents)
                    // Note that disposing the documents immediately after engine execution will ensure write streams get flushed and released
                    // but will also mean that callers (and tests) can't access documents and document content after the engine finishes
                    // Easiest way to access content after engine execution is to add a final Meta module and copy content to metadata
                    ExecutionCacheManager.ClearUnhitEntries();
                    foreach (IPipeline pipeline in _pipelines.Pipelines)
                    {
                        ((ExecutionPipeline)pipeline).ResetClonedDocuments();
                    }

                    engineStopwatch.Stop();
                    Trace.Information(
                        "Executed {0}/{1} pipelines in {2} ms",
                        c - 1,
                        _pipelines.Count,
                        engineStopwatch.ElapsedMilliseconds);
                }
            }
            catch (Exception ex)
            {
                Trace.Critical("Exception during execution: {0}", ex.ToString());
                throw;
            }
        }
Ejemplo n.º 20
0
        protected override ExitCode RunCommand(Preprocessor preprocessor)
        {
            // Make sure we actually got a recipe value
            if (preprocessor.Values.All(x => x.Name != "recipe"))
            {
                Trace.Critical("A recipe must be specified");
                return(ExitCode.CommandLineError);
            }

            _configOptions.RootPath = Environment.CurrentDirectory;
            _path = _path ?? "input";

            // Get the engine and configurator
            using (EngineManager engineManager = EngineManager.Get(preprocessor, _configOptions))
            {
                if (engineManager == null)
                {
                    return(ExitCode.CommandLineError);
                }

                // Check to make sure the directory is empty (and provide option to clear it)
                IDirectory scaffoldDirectory = engineManager.Engine.FileSystem.GetRootDirectory(_path);
                if (scaffoldDirectory.Exists)
                {
                    Console.WriteLine($"Scaffold directory {scaffoldDirectory.Path.FullPath} exists, are you sure you want to clear it [y|N]?");
                    char inputChar = Console.ReadKey(true).KeyChar;
                    if (inputChar != 'y' && inputChar != 'Y')
                    {
                        Trace.Information($"Scaffold directory will not be cleared");
                        return(ExitCode.Normal);
                    }
                    Trace.Information($"Scaffold directory will be cleared");
                }
                else
                {
                    Trace.Information($"Scaffold directory {scaffoldDirectory.Path.FullPath} does not exist and will be created");
                }
                if (scaffoldDirectory.Exists)
                {
                    scaffoldDirectory.Delete(true);
                }
                scaffoldDirectory.Create();

                // We can ignore theme packages since we don't care about the theme for scaffolding
                engineManager.Configurator.IgnoreKnownThemePackages = true;

                // Configure everything (primarily to get the recipe)
                try
                {
                    engineManager.Configurator.Configure(null);
                }
                catch (Exception ex)
                {
                    Trace.Critical("Error while configuring engine: {0}", ex.Message);
                    return(ExitCode.ConfigurationError);
                }

                // Scaffold the recipe
                engineManager.Configurator.Recipe.Scaffold(scaffoldDirectory);
            }

            return(ExitCode.Normal);
        }
Ejemplo n.º 21
0
        public void Execute()
        {
            CheckDisposed();

            // Configure with defaults if not already configured
            if (!_config.Configured)
            {
                Configure();
            }

            // Clean the output folder if requested
            if (Settings.CleanOutputPath)
            {
                CleanOutputPath();
            }

            // Create the output folder if it doesn't already exist
            IDirectory outputDirectory = FileSystem.GetOutputDirectory();

            if (!outputDirectory.Exists)
            {
                outputDirectory.Create();
            }

            try
            {
                System.Diagnostics.Stopwatch engineStopwatch = System.Diagnostics.Stopwatch.StartNew();
                using (Trace.WithIndent().Information("Executing {0} pipelines", _pipelines.Count))
                {
                    // Setup (clear the document collection and reset cache counters)
                    DocumentCollection.Clear();
                    ExecutionCacheManager.ResetEntryHits();

                    // Enumerate pipelines and execute each in order
                    int c = 1;
                    foreach (Pipeline pipeline in _pipelines.Pipelines)
                    {
                        string pipelineName = pipeline.Name;
                        System.Diagnostics.Stopwatch pipelineStopwatch = System.Diagnostics.Stopwatch.StartNew();
                        using (Trace.WithIndent().Information("Executing pipeline \"{0}\" ({1}/{2}) with {3} child module(s)", pipelineName, c, _pipelines.Count, pipeline.Count))
                        {
                            try
                            {
                                pipeline.Execute(this);
                                pipelineStopwatch.Stop();
                                Trace.Information("Executed pipeline \"{0}\" ({1}/{2}) in {3} ms resulting in {4} output document(s)",
                                                  pipelineName, c++, _pipelines.Count, pipelineStopwatch.ElapsedMilliseconds,
                                                  DocumentCollection.FromPipeline(pipelineName).Count());
                            }
                            catch (Exception)
                            {
                                Trace.Error("Error while executing pipeline {0}", pipelineName);
                                throw;
                            }
                        }
                    }

                    // Clean up (clear unhit cache entries, dispose documents)
                    // Note that disposing the documents immediately after engine execution will ensure write streams get flushed and released
                    // but will also mean that callers (and tests) can't access documents and document content after the engine finishes
                    // Easiest way to access content after engine execution is to add a final Meta module and copy content to metadata
                    ExecutionCacheManager.ClearUnhitEntries();
                    foreach (Pipeline pipeline in _pipelines.Pipelines)
                    {
                        pipeline.ResetClonedDocuments();
                    }

                    engineStopwatch.Stop();
                    Trace.Information("Executed {0}/{1} pipelines in {2} ms",
                                      c - 1, _pipelines.Count, engineStopwatch.ElapsedMilliseconds);
                }
            }
            catch (Exception ex)
            {
                Trace.Critical("Exception during execution: {0}", ex.ToString());
                throw;
            }
        }