Пример #1
0
 public ConsumerService()
 {
     logger = HostLogger.Get <ConsumerService>();
 }
Пример #2
0
 public UploadAttendanceHandler(Bundle bundle)
 {
     Bundle = bundle;
     Logger = HostLogger.Get <UploadAttendanceHandler>();
 }
Пример #3
0
        private static int Main(string[] argv)
        {
            int port = -1;

            // parse command line arguments
            foreach (var a in argv)
            {
                if ((a == null) || (a == "undefined"))
                {
                    continue;
                }
                switch (a)
                {
                case "-h":
                case "-?":
                case "/?":
                case "--help":
                    Console.WriteLine("OpenDebugAD7: Visual Studio Code debug adapter bridge for using Visual Studio");
                    Console.WriteLine("debug engines in VS Code");
                    Console.WriteLine();
                    Console.WriteLine("Available command line arguments:");
                    Console.WriteLine("--trace: print the requests coming from VS Code to the console.");
                    Console.WriteLine("--trace=response: print requests and response from VS Code to the console.");
                    Console.WriteLine("--engineLogging[=filePath]: Enable logging from the debug engine. If not");
                    Console.WriteLine("    specified, the log will go to the console.");
                    Console.WriteLine("--server[=port_num] : Start the debug adapter listening for requests on the");
                    Console.WriteLine("    specified TCP/IP port instead of stdin/out. If port is not specified");
                    Console.WriteLine("    TCP {0} will be used.", DEFAULT_PORT);
                    Console.WriteLine("--pauseForDebugger: Pause the OpenDebugAD7.exe process at startup until a");
                    Console.WriteLine("    debugger attaches.");
                    return(1);

                case "--trace":
                    s_trace_requests = true;
                    break;

                case "--trace=response":
                    s_trace_requests  = true;
                    s_trace_responses = true;
                    break;

                case "--engineLogging":
                    s_engine_logging = true;
                    HostLogger.EnableHostLogging();
                    break;

                case "--server":
                    port = DEFAULT_PORT;
                    break;

                case "--pauseForDebugger":
                    Console.WriteLine("OpenDebugAD7.exe is waiting for a managed debugger to attach to it.");
                    while (!Debugger.IsAttached)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    break;

                default:
                    if (a.StartsWith("--server=", StringComparison.Ordinal))
                    {
                        string portString = a.Substring("--server=".Length);
                        if (!int.TryParse(portString, out port))
                        {
                            Console.Error.WriteLine("OpenDebugAD7: ERROR: Unable to parse port string '{0}'.", portString);
                            return(-1);
                        }
                    }
                    else if (a.StartsWith("--engineLogging=", StringComparison.Ordinal))
                    {
                        HostLogger.EnableHostLogging();
                        try
                        {
                            HostLogger.Instance.LogFilePath = a.Substring("--engineLogging=".Length);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine("OpenDebugAD7: ERROR: Unable to open log file. " + e.Message);
                            return(-1);
                        }
                    }
                    else if (a.StartsWith("--adapterDirectory=", StringComparison.Ordinal))
                    {
                        string adapterDirectory = a.Substring("--adapterDirectory=".Length);
                        if (!Directory.Exists(adapterDirectory))
                        {
                            Console.Error.WriteLine("OpenDebugAD7: ERROR: adapter directory '{0}' does not exist.", adapterDirectory);
                            return(-1);
                        }
                        EngineConfiguration.SetAdapterDirectory(adapterDirectory);
                    }
                    else
                    {
                        Console.Error.WriteLine("OpenDebugAD7: ERROR: Unknown command line argument '{0}'.", a);
                        return(-1);
                    }
                    break;
                }
            }

#if !CORECLR
            if (Utilities.IsMono())
            {
                // Mono uses the threadpool heavily for its async/await implementation.  Make sure we have an acceptable
                //  lower limit on the threadpool size to avoid deadlocks.
                int currentMinWorkerThreads, currentMinIOCThreads;
                ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIOCThreads);

                if (currentMinWorkerThreads < 8)
                {
                    ThreadPool.SetMinThreads(8, currentMinIOCThreads);
                }
            }
#endif

            if (port > 0)
            {
                // TCP/IP server
                RunServer(port);
            }

            try
            {
                // stdin/stdout
                Console.Error.WriteLine("waiting for v8 protocol on stdin/stdout");
                Dispatch(Console.OpenStandardInput(), Console.OpenStandardOutput());
            }
            catch (Exception e)
            {
                Utilities.ReportException(e);
            }

            return(0);
        }
Пример #4
0
 public static void Use()
 {
     HostLogger.UseLogger(new Log4NetLoggerConfigurator(null));
 }
 internal static void Use()
 {
     HostLogger.UseLogger(new CommonLoggingConfigurator());
 }
Пример #6
0
        public TopshelfExitCode Run()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException;

            if (_environment.IsServiceInstalled(_settings.ServiceName))
            {
                if (!_environment.IsServiceStopped(_settings.ServiceName))
                {
                    _log.ErrorFormat("The {0} service is running and must be stopped before running via the console",
                                     _settings.ServiceName);

                    return(TopshelfExitCode.ServiceAlreadyRunning);
                }
            }

            bool started = false;

            try
            {
                _log.Debug("Starting up as a console application");

                _exit     = new ManualResetEvent(false);
                _exitCode = TopshelfExitCode.Ok;

                Console.Title           = _settings.DisplayName;
                Console.CancelKeyPress += HandleCancelKeyPress;

                if (!_serviceHandle.Start(this))
                {
                    throw new TopshelfException("The service failed to start (return false).");
                }

                started = true;

                _log.InfoFormat("The {0} service is now running, press Control+C to exit.", _settings.ServiceName);

                _exit.WaitOne();
            }
            catch (Exception ex)
            {
                _log.Error("An exception occurred", ex);

                return(TopshelfExitCode.AbnormalExit);
            }
            finally
            {
                if (started)
                {
                    StopService();
                }

                _exit.Close();
                (_exit as IDisposable).Dispose();

                HostLogger.Shutdown();
            }

            return(_exitCode);
        }
Пример #7
0
 /// <summary>Reports content of the host logger to user.</summary>
 /// <param name="logger">The host logger.</param>
 /// <param name="summary">The summary to report.</param>
 protected abstract void ReportHostLogger([NotNull] HostLogger logger, [CanBeNull] Summary summary);
Пример #8
0
 /// <summary>
 ///   Specify that you want to use the Serilog logging engine.
 /// </summary>
 /// <param name="configurator"></param>
 public static void UseSerilog(this HostConfigurator configurator)
 {
     HostLogger.UseLogger(new SerilogHostLoggerConfigurator());
 }
Пример #9
0
 void HostControl.Stop(TopshelfExitCode exitCode)
 {
     _log.Info($"Application Stop requested, exiting with exit code: {exitCode}.");
     StopService();
     HostLogger.Shutdown();
 }
 public AzureBlobBuilderExtensionShould()
 {
     HostLogger.UseLogger(new TraceHostLoggerConfigurator());
 }
Пример #11
0
        public ResendAttendanceHandler(Bundle bundle)
        {
            Bundle = bundle;

            Logger = HostLogger.Get <ResendAttendanceHandler>();
        }
Пример #12
0
 /// <summary>Reports content of the host logger to user.</summary>
 /// <param name="logger">The host logger.</param>
 /// <param name="summary">The summary to report.</param>
 protected override void ReportHostLogger(HostLogger logger, Summary summary)
 {
     // Do nothing.
 }
Пример #13
0
 public SyncService()
 {
     _logger = HostLogger.Get <SyncService>();
     _logger.Debug("Began SyncService init");
 }
 /// <summary>
 ///   Specify that you want to use the NLog logging framework.
 /// </summary>
 /// <param name="configurator"> Optional service bus configurator </param>
 /// <param name="factory"> Required log-producing factory from NLog </param>
 public static void UseNLog(this HostConfigurator configurator, LogFactory factory)
 {
     HostLogger.UseLogger(new NLogLogWriterFactory(factory));
 }
Пример #15
0
 /// <summary>Reports content of the host logger to user.</summary>
 /// <param name="logger">The host logger.</param>
 /// <param name="summary">The summary to report.</param>
 protected override void ReportHostLogger(HostLogger logger, Summary summary)
 {
     // Nothing to do here, ConsoleHostLogger dumps output directly to the console.
 }
Пример #16
0
        public FailedMessageHandler(Bundle bundle)
        {
            Bundle = bundle;

            Logger = HostLogger.Get <FailedMessageHandler>();
        }
Пример #17
0
 public static void UseEventLog(this HostConfigurator configurator, BottleServiceConfiguration settings)
 {
     HostLogger.UseLogger(new EventLogFactoryConfigurator(settings));
 }
Пример #18
0
        private static int Main(string[] argv)
        {
            int port = -1;
            List <LoggingCategory> loggingCategories = new List <LoggingCategory>();

            // parse command line arguments
            foreach (var a in argv)
            {
                if ((a == null) || (a == "undefined"))
                {
                    continue;
                }
                switch (a)
                {
                case "-h":
                case "-?":
                case "/?":
                case "--help":
                    Console.WriteLine("OpenDebugAD7: Visual Studio Code debug adapter bridge for using Visual Studio");
                    Console.WriteLine("debug engines in VS Code");
                    Console.WriteLine();
                    Console.WriteLine("Available command line arguments:");
                    Console.WriteLine("--trace: print the requests coming from VS Code to the console.");
                    Console.WriteLine("--trace=response: print requests and response from VS Code to the console.");
                    Console.WriteLine("--engineLogging[=filePath]: Enable logging from the debug engine. If not");
                    Console.WriteLine("    specified, the log will go to the console.");
                    Console.WriteLine("--server[=port_num] : Start the debug adapter listening for requests on the");
                    Console.WriteLine("    specified TCP/IP port instead of stdin/out. If port is not specified");
                    Console.WriteLine("    TCP {0} will be used.", DEFAULT_PORT);
                    Console.WriteLine("--pauseForDebugger: Pause the OpenDebugAD7.exe process at startup until a");
                    Console.WriteLine("    debugger attaches.");
                    return(1);

                case "--trace":
                    loggingCategories.Add(LoggingCategory.AdapterTrace);
                    break;

                case "--trace=response":
                    loggingCategories.Add(LoggingCategory.AdapterTrace);
                    loggingCategories.Add(LoggingCategory.AdapterResponse);
                    break;

                case "--engineLogging":
                    loggingCategories.Add(LoggingCategory.EngineLogging);
                    HostLogger.EnableHostLogging();
                    break;

                case "--server":
                    port = DEFAULT_PORT;
                    break;

                case "--pauseForDebugger":
                    Console.WriteLine("OpenDebugAD7.exe is waiting for a managed debugger to attach to it.");
                    while (!Debugger.IsAttached)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    break;

                default:
                    if (a.StartsWith("--server=", StringComparison.Ordinal))
                    {
                        string portString = a.Substring("--server=".Length);
                        if (!int.TryParse(portString, out port))
                        {
                            Console.Error.WriteLine("OpenDebugAD7: ERROR: Unable to parse port string '{0}'.", portString);
                            return(-1);
                        }
                    }
                    else if (a.StartsWith("--engineLogging=", StringComparison.Ordinal))
                    {
                        HostLogger.EnableHostLogging();
                        try
                        {
                            HostLogger.Instance.LogFilePath = a.Substring("--engineLogging=".Length);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine("OpenDebugAD7: ERROR: Unable to open log file. " + e.Message);
                            return(-1);
                        }
                    }
                    else if (a.StartsWith("--adapterDirectory=", StringComparison.Ordinal))
                    {
                        string adapterDirectory = a.Substring("--adapterDirectory=".Length);
                        if (!Directory.Exists(adapterDirectory))
                        {
                            Console.Error.WriteLine("OpenDebugAD7: ERROR: adapter directory '{0}' does not exist.", adapterDirectory);
                            return(-1);
                        }
                        EngineConfiguration.SetAdapterDirectory(adapterDirectory);
                    }
                    else
                    {
                        Console.Error.WriteLine("OpenDebugAD7: ERROR: Unknown command line argument '{0}'.", a);
                        return(-1);
                    }
                    break;
                }
            }

            if (port > 0)
            {
                // TCP/IP server
                RunServer(port, loggingCategories);
            }

            try
            {
                // stdin/stdout
                Console.Error.WriteLine("waiting for v8 protocol on stdin/stdout");
                if (Utilities.IsWindows())
                {
                    // Avoid sending the BOM on Windows if the Beta Unicode feature is enabled in Windows 10
                    Console.OutputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
                    Console.InputEncoding  = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
                }
                Dispatch(Console.OpenStandardInput(), Console.OpenStandardOutput(), loggingCategories);
            }
            catch (Exception e)
            {
                Utilities.ReportException(e);
            }

            return(0);
        }
Пример #19
0
 public LinuxHostEnvironmentImpl(HostConfigurator configurator, IDictionary <string, object> arguments)
 {
     _configurator = configurator;
     _arguments    = arguments;
     _logWriter    = HostLogger.Get <LinuxHostEnvironmentImpl>();
 }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Configure job. </summary>
        ///
        /// <typeparam name="T">    Generic type parameter. </typeparam>
        /// <param name="configurator">     The configurator. </param>
        /// <param name="jobConfigurator">  The job configurator. </param>
        /// <param name="replaceJob">       (Optional) True to replace job. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        private static void ConfigureJob <T>(ServiceConfigurator <T> configurator, Action <QuartzConfigurator> jobConfigurator, bool replaceJob = false) where T : class
        {
            var log = HostLogger.Get(typeof(ScheduleJobServiceConfiguratorExtensions));

            var jobConfig = new QuartzConfigurator();

            jobConfigurator(jobConfig);

            if (jobConfig.JobEnabled == null || jobConfig.JobEnabled() || (jobConfig.Job == null || jobConfig.Triggers == null))
            {
                var jobDetail         = jobConfig.Job();
                var jobTriggers       = jobConfig.Triggers.Select(triggerFactory => triggerFactory()).Where(trigger => trigger != null);
                var jobListeners      = jobConfig.JobListeners;
                var triggerListeners  = jobConfig.TriggerListeners;
                var scheduleListeners = jobConfig.ScheduleListeners;
                configurator.BeforeStartingService((context) =>
                {
                    log.Debug("[Topshelf.Quartz] Scheduler starting up...");
                    if (Scheduler == null)
                    {
                        Scheduler = GetScheduler();
                    }


                    if (Scheduler != null && jobDetail != null && jobTriggers.Any())
                    {
                        var triggersForJob = new HashSet <ITrigger>(jobTriggers);
                        Scheduler.ScheduleJob(jobDetail, triggersForJob, replaceJob);
                        log.Info(string.Format("[Topshelf.Quartz] Scheduled Job: {0}", jobDetail.Key));

                        foreach (var trigger in triggersForJob)
                        {
                            log.Info(string.Format("[Topshelf.Quartz] Job Schedule: {0} - Next Fire Time (local): {1}", trigger, trigger.GetNextFireTimeUtc().HasValue ? trigger.GetNextFireTimeUtc().Value.ToLocalTime().ToString() : "none"));
                        }

                        if (jobListeners.Any())
                        {
                            foreach (var listener in jobListeners)
                            {
                                var config = listener();
                                Scheduler.ListenerManager.AddJobListener(
                                    config.Listener, config.Matchers as IReadOnlyCollection <IMatcher <JobKey> >);
                                log.Info(
                                    $"[Topshelf.Quartz] Added Job Listener: {config.Listener.Name}");
                            }
                        }

                        if (triggerListeners.Any())
                        {
                            foreach (var listener in triggerListeners)
                            {
                                var config = listener();
                                Scheduler.ListenerManager.AddTriggerListener(config.Listener, config.Matchers as IReadOnlyCollection <IMatcher <TriggerKey> >);
                                log.Info(
                                    string.Format(
                                        "[Topshelf.Quartz] Added Trigger Listener: {0}",
                                        config.Listener.Name));
                            }
                        }
                        if (scheduleListeners.Any())
                        {
                            foreach (var listener in scheduleListeners)
                            {
                                var schedListener = listener();
                                Scheduler.ListenerManager.AddSchedulerListener(schedListener);
                                string.Format(
                                    "[Topshelf.Quartz] Added Schedule Listener: {0}",
                                    schedListener.GetType());
                            }
                        }

                        Scheduler.Start();
                        log.Info("[Topshelf.Quartz] Scheduler started...");
                    }
                });

                configurator.BeforeStoppingService((context) =>
                {
                    log.Debug("[Topshelf.Quartz] Scheduler shutting down...");
                    if (Scheduler != null)
                    {
                        if (!Scheduler.IsShutdown)
                        {
                            Scheduler.Shutdown();
                        }
                    }
                    log.Info("[Topshelf.Quartz] Scheduler shut down...");
                });
            }
        }
Пример #21
0
 private static void ConfigureService(ServiceConfigurator <WindowsService> serviceConfigurator)
 {
     serviceConfigurator.ConstructUsing(() => new WindowsService(HostLogger.Get(Name)));
     serviceConfigurator.WhenStarted(service => service.OnStart());
     serviceConfigurator.WhenStopped(service => service.OnStop());
 }
Пример #22
0
        private static void Dispatch(Stream inputStream, Stream outputStream)
        {
            DispatcherProtocol protocol = new DispatcherProtocol(inputStream, outputStream);

            Action <string> traceResponseCallback = s => Console.Error.WriteLine(s);

            if (s_trace_requests)
            {
                protocol.TraceCallback = traceResponseCallback;
            }

            if (s_trace_responses)
            {
                protocol.ResponseCallback = traceResponseCallback;
            }

            if (s_engine_logging && HostLogger.Instance?.LogFilePath == null)
            {
                HostLogger.Instance.LogCallback = s => Console.WriteLine(s);
            }

            IDebugSession debugSession = null;

            protocol.Start((string command, dynamic args, IResponder responder) =>
            {
                if (args == null)
                {
                    args = new { };
                }

                if (command == "initialize")
                {
                    string adapterID = Utilities.GetString(args, "adapterID");
                    if (adapterID == null)
                    {
                        responder.SetBody(new ErrorResponseBody(new Message(1101, "initialize: property 'adapterID' is missing or empty")));
                        return;
                    }

                    DebugProtocolCallbacks debugProtocolCallbacks = new DebugProtocolCallbacks()
                    {
                        Send              = e => protocol.SendEvent(e.type, e),
                        SendRaw           = e => protocol.SendRawEvent(e.type, e),
                        SendLater         = e => protocol.SendEventLater(e.type, e),
                        SetTraceLogger    = t => protocol.TraceCallback = t,
                        SetResponseLogger = t => protocol.ResponseCallback = t,
                        SetEngineLogger   = t =>
                        {
                            HostLogger.EnableHostLogging();
                            HostLogger.Instance.LogCallback = t;
                        }
                    };

                    debugSession = OpenDebugAD7.EngineFactory.CreateDebugSession(adapterID, debugProtocolCallbacks);
                    if (debugSession == null)
                    {
                        responder.SetBody(new ErrorResponseBody(new Message(1103, "initialize: can't create debug session for adapter '{_id}'", new { _id = adapterID })));
                        return;
                    }
                }

                if (debugSession != null)
                {
                    try
                    {
                        DebugResult dr = debugSession.Dispatch(command, args);
                        if (dr != null)
                        {
                            responder.SetBody(dr.Body);

                            if (dr.Events != null)
                            {
                                foreach (var e in dr.Events)
                                {
                                    responder.AddEvent(e.type, e);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        AggregateException aggregateException = e as AggregateException;
                        bool bodySet = false;
                        if (aggregateException != null)
                        {
                            if (aggregateException.InnerExceptions.Count == 1)
                            {
                                e = aggregateException.InnerException;
                            }
                            else
                            {
                                string exceptionMessages = string.Join(", ", aggregateException.InnerExceptions.Select((x) => Utilities.GetExceptionDescription(x)));
                                responder.SetBody(new ErrorResponseBody(new Message(1104, "error while processing request '{_request}' (exceptions: {_messages})", new { _request = command, _messages = exceptionMessages })));
                                bodySet = true;
                            }
                        }

                        if (!bodySet)
                        {
                            if (Utilities.IsCorruptingException(e))
                            {
                                Utilities.ReportException(e);
                            }

                            if (e is OpenDebugAD7.AD7Exception)
                            {
                                responder.SetBody(new ErrorResponseBody(new Message(1104, e.Message)));
                            }
                            else
                            {
                                responder.SetBody(new ErrorResponseBody(new Message(1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = Utilities.GetExceptionDescription(e) })));
                            }
                        }
                    }

                    if (command == "disconnect")
                    {
                        protocol.Stop();
                    }
                }
            }).Wait();
        }
Пример #23
0
 /// <summary>
 /// Create a new Editor Services loader.
 /// </summary>
 /// <param name="logger">The host logger to use.</param>
 /// <param name="hostConfig">The host configuration to start editor services with.</param>
 /// <param name="sessionFileWriter">The session file writer to write the session file with.</param>
 /// <returns></returns>
 public static EditorServicesLoader Create(
     HostLogger logger,
     EditorServicesConfig hostConfig,
     ISessionFileWriter sessionFileWriter) => Create(logger, hostConfig, sessionFileWriter, loggersToUnsubscribe: null);
 /// <summary>
 /// Construct a new session file writer for the given session file path.
 /// </summary>
 /// <param name="logger">The logger to log actions with.</param>
 /// <param name="sessionFilePath">The path to write the session file path to.</param>
 public SessionFileWriter(HostLogger logger, string sessionFilePath)
 {
     _logger          = logger;
     _sessionFilePath = sessionFilePath;
 }
Пример #25
0
        /// <summary>
        /// Create a new Editor Services loader.
        /// </summary>
        /// <param name="logger">The host logger to use.</param>
        /// <param name="hostConfig">The host configuration to start editor services with.</param>
        /// <param name="sessionFileWriter">The session file writer to write the session file with.</param>
        /// <returns></returns>
        public static EditorServicesLoader Create(
            HostLogger logger,
            EditorServicesConfig hostConfig,
            ISessionFileWriter sessionFileWriter,
            IReadOnlyCollection <IDisposable> loggersToUnsubscribe)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (hostConfig == null)
            {
                throw new ArgumentNullException(nameof(hostConfig));
            }

#if CoreCLR
            // In .NET Core, we add an event here to redirect dependency loading to the new AssemblyLoadContext we load PSES' dependencies into
            logger.Log(PsesLogLevel.Verbose, "Adding AssemblyResolve event handler for new AssemblyLoadContext dependency loading");

            var psesLoadContext = new PsesLoadContext(s_psesDependencyDirPath);

            if (hostConfig.LogLevel == PsesLogLevel.Diagnostic)
            {
                AppDomain.CurrentDomain.AssemblyLoad += (object sender, AssemblyLoadEventArgs args) =>
                {
                    logger.Log(
                        PsesLogLevel.Diagnostic,
                        $"Loaded into load context {AssemblyLoadContext.GetLoadContext(args.LoadedAssembly)}: {args.LoadedAssembly}");
                };
            }

            AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext defaultLoadContext, AssemblyName asmName) =>
            {
                logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {asmName}");

                // We only want the Editor Services DLL; the new ALC will lazily load its dependencies automatically
                if (!string.Equals(asmName.Name, "Microsoft.PowerShell.EditorServices", StringComparison.Ordinal))
                {
                    return(null);
                }

                string asmPath = Path.Combine(s_psesDependencyDirPath, $"{asmName.Name}.dll");

                logger.Log(PsesLogLevel.Verbose, "Loading PSES DLL using new assembly load context");

                return(psesLoadContext.LoadFromAssemblyPath(asmPath));
            };
#else
            // In .NET Framework we add an event here to redirect dependency loading in the current AppDomain for PSES' dependencies
            logger.Log(PsesLogLevel.Verbose, "Adding AssemblyResolve event handler for dependency loading");

            if (hostConfig.LogLevel == PsesLogLevel.Diagnostic)
            {
                AppDomain.CurrentDomain.AssemblyLoad += (object sender, AssemblyLoadEventArgs args) =>
                {
                    logger.Log(
                        PsesLogLevel.Diagnostic,
                        $"Loaded '{args.LoadedAssembly.GetName()}' from '{args.LoadedAssembly.Location}'");
                };
            }

            // Unlike in .NET Core, we need to be look for all dependencies in .NET Framework, not just PSES.dll
            AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) =>
            {
                logger.Log(PsesLogLevel.Diagnostic, $"Assembly resolve event fired for {args.Name}");

                var asmName = new AssemblyName(args.Name);
                var dllName = $"{asmName.Name}.dll";

                // First look for the required assembly in the .NET Framework DLL dir
                string baseDirAsmPath = Path.Combine(s_psesBaseDirPath, dllName);
                if (File.Exists(baseDirAsmPath))
                {
                    logger.Log(PsesLogLevel.Diagnostic, $"Loading {args.Name} from PSES base dir into LoadFile context");
                    return(Assembly.LoadFile(baseDirAsmPath));
                }

                // Then look in the shared .NET Standard directory
                string asmPath = Path.Combine(s_psesDependencyDirPath, dllName);
                if (File.Exists(asmPath))
                {
                    logger.Log(PsesLogLevel.Diagnostic, $"Loading {args.Name} from PSES dependency dir into LoadFile context");
                    return(Assembly.LoadFile(asmPath));
                }

                return(null);
            };
#endif

            return(new EditorServicesLoader(logger, hostConfig, sessionFileWriter, loggersToUnsubscribe));
        }
Пример #26
0
 public static void Use(string file)
 {
     HostLogger.UseLogger(new Log4NetLoggerConfigurator(file));
 }
Пример #27
0
        public TopshelfExitCode Run()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            AppDomain.CurrentDomain.UnhandledException += CatchUnhandledException;

#if NETCORE
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
#endif
            if (_environment.IsServiceInstalled(_settings.ServiceName))
            {
                if (!_environment.IsServiceStopped(_settings.ServiceName))
                {
                    _log.ErrorFormat(
                        "The {0} service is running and must be stopped before running via the console",
                        _settings.ServiceName);

                    return(TopshelfExitCode.ServiceAlreadyRunning);
                }
            }
#if NETCORE
        }
#endif

            bool started = false;
            try
            {
                _log.Debug("Starting up as a console application");

                _exit     = new ManualResetEvent(false);
                _exitCode = TopshelfExitCode.Ok;
                if (
#if NETCORE
                    !RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
#endif
                    IntPtr.Zero != GetConsoleWindow())
                {
                    try
                    {
                        // It is common to run console applications in windowless mode, this prevents
                        // the process from crashing when attempting to set the title.
                        Console.Title = _settings.DisplayName;
                    }
                    catch (Exception e) when(e is IOException || e is PlatformNotSupportedException)
                    {
                        _log.Info("It was not possible to set the console window title. See the inner exception for details.", e);
                    }
                }
                Console.CancelKeyPress += HandleCancelKeyPress;

                if (!_serviceHandle.Start(this))
                {
                    throw new TopshelfException("The service failed to start (return false).");
                }

                started = true;

                _log.InfoFormat("The {0} service is now running, press Control+C to exit.", _settings.ServiceName);

                _exit.WaitOne();
            }
            catch (Exception ex)
            {
                _settings.ExceptionCallback?.Invoke(ex);

                _log.Error("An exception occurred", ex);

                return(TopshelfExitCode.AbnormalExit);
            }
            finally
            {
                if (started)
                {
                    StopService();
                }

                _exit.Close();
                (_exit as IDisposable).Dispose();

                HostLogger.Shutdown();
            }

            return(_exitCode);
        }