Ejemplo n.º 1
0
        /// <summary>
        /// BRE debugger
        /// </summary>
        /// <param name="sources"></param>
        public BreDebugger(DebuggerParameters parms) : base(parms.WorkingDirectory)
        {
            Console.WriteLine("Starting debugger...");
            DebugApplicationContext.Start(parms);
            ApplicationServiceContext.Current = ApplicationContext.Current;
            ApplicationContext.Current.AddServiceProvider(typeof(FileSystemResolver));
            ApplicationContext.Current.AddServiceProvider(typeof(ServiceManager));
            Tracer.AddWriter(new ConsoleTraceWriter(EventLevel.LogAlways, "dbg"), EventLevel.LogAlways);

            if (!String.IsNullOrEmpty(parms.WorkingDirectory))
            {
                ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory = parms.WorkingDirectory;
            }
            var rootPath = ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory;

            // Load debug targets
            Console.WriteLine("Loading debuggees...");
            if (parms.Sources != null)
            {
                foreach (var rf in parms.Sources)
                {
                    var f = rf.Replace("~", rootPath);
                    if (!File.Exists(f))
                    {
                        Console.Error.WriteLine("Can't find file {0}", f);
                    }
                    else
                    {
                        this.Execute(f);
                    }
                }
            }
            JavascriptBusinessRulesEngine.SetDebugMode(true);
            JavascriptBusinessRulesEngine.Current.Engine.Step += JreStep;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Start the application context
        /// </summary>
        public bool Start()
        {
            if (!this.IsRunning)
            {
                Stopwatch startWatch = new Stopwatch();

                try
                {
                    startWatch.Start();

                    if (this.Starting != null)
                    {
                        this.Starting(this, null);
                    }

                    // If there is no configuration manager then add the local
                    Trace.TraceInformation("STAGE0 START: Load Configuration");

                    // Assign diagnostics
                    var config = this.GetService <IConfigurationManager>().GetSection <DiagnosticsConfigurationSection>();

                    if (config != null)
                    {
                        foreach (var writer in config.TraceWriter)
                        {
                            Tracer.AddWriter(Activator.CreateInstance(writer.TraceWriter, writer.Filter, writer.InitializationData, config.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, writer.Filter);
                        }
                    }
#if DEBUG
                    else
                    {
                        Tracer.AddWriter(new SanteDB.Core.Diagnostics.Tracing.SystemDiagnosticsTraceWriter(), System.Diagnostics.Tracing.EventLevel.LogAlways);
                    }
#endif

                    this.m_tracer.TraceInfo("STAGE1 START: Start Dependency Injection Manager");
                    this.m_serviceProvider.AddServiceProvider(this);
                    this.m_serviceProvider.Start();

                    this.m_tracer.TraceInfo("STAGE2 START: Notify start");
                    this.Started?.Invoke(this, EventArgs.Empty);
                    this.StartTime = DateTime.Now;
                }
                finally
                {
                    startWatch.Stop();
                }
                this.IsRunning = true;
            }

            return(true);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Starts the application context using in-memory default configuration for the purposes of
        /// configuring the software
        /// </summary>
        /// <returns><c>true</c>, if temporary was started, <c>false</c> otherwise.</returns>
        public static bool StartTemporary(IDialogProvider dialogProvider, String instanceName, SecurityApplication applicationId, SanteDBHostType hostType)
        {
            try
            {
                var retVal = new DcApplicationContext(dialogProvider, instanceName, applicationId, hostType);
                retVal.SetProgress("Run setup", 0);
                //retVal.AddServiceProvider(typeof(ConfigurationManager));
                ApplicationServiceContext.Current = DcApplicationContext.Current = retVal;
                retVal.m_tracer = Tracer.GetTracer(typeof(DcApplicationContext));
                var configuration = retVal.Configuration.GetSection <DiagnosticsConfigurationSection>();
                foreach (var tr in configuration.TraceWriter)
                {
                    Tracer.AddWriter(Activator.CreateInstance(tr.TraceWriter, tr.Filter, tr.InitializationData, configuration.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, tr.Filter);
                }
                retVal.GetService <IServiceManager>().AddServiceProvider(typeof(DefaultBackupService));

                var appletService = retVal.GetService <IAppletManagerService>();

                retVal.SetProgress("Loading configuration", 0.2f);
                // Load all user-downloaded applets in the data directory
                foreach (var appPath in Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "applets")))
                {
                    try
                    {
                        retVal.m_tracer.TraceInfo("Installing applet {0}", appPath);
                        using (var fs = File.OpenRead(appPath))
                        {
                            AppletPackage package = AppletPackage.Load(fs);
                            appletService.Install(package, true);
                        }
                    }
                    catch (Exception e)
                    {
                        retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appPath, e.ToString());
                        throw;
                    }
                }

                retVal.GetService <IThreadPoolService>().QueueUserWorkItem((o) => retVal.Start());

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("SanteDB FATAL: {0}", e.ToString());
                return(false);
            }
        }
Ejemplo n.º 4
0
            public AdminShell()
            {
                AuthenticationContext.Current     = new AuthenticationContext(AuthenticationContext.AnonymousPrincipal);
                ApplicationServiceContext.Current = ApplicationContext.Current;
                ApplicationContext.Current.AddServiceProvider(typeof(ServiceManager));
                System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener()
                {
                    Filter = new EventTypeFilter(SourceLevels.Warning | SourceLevels.Error)
                });

                ApplicationContext.Current.Start();

                Tracer.AddWriter(new ConsoleTraceWriter(EventLevel.LogAlways, "dbg"), EventLevel.LogAlways);
                Console.Clear();
                Console.WriteLine("Open Administration Console v{0}", typeof(Program).Assembly.GetName().Version);
                Console.WriteLine("Copyright (C) 2015 - 2017, Mohawk College of Applied Arts and Technology");

                this.m_prompt = "> ";
            }
Ejemplo n.º 5
0
        /// <summary>
        /// BRE debugger
        /// </summary>
        /// <param name="sources"></param>
        public ProtoDebugger(DebuggerParameters parms) : base(parms.WorkingDirectory)
        {
            Console.WriteLine("Starting debugger...");

            DebugApplicationContext.Start(parms);
            ApplicationServiceContext.Current = ApplicationContext.Current;
            try
            {
                ApplicationContext.Current.RemoveServiceProvider(typeof(IClinicalProtocolRepositoryService));
            }
            catch { }

            ApplicationContext.Current.AddServiceProvider(typeof(FileSystemResolver));
            ApplicationContext.Current.AddServiceProvider(typeof(ServiceManager));
            ApplicationContext.Current.AddServiceProvider(typeof(DebugProtocolRepository));
            Tracer.AddWriter(new ConsoleTraceWriter(EventLevel.LogAlways, "dbg"), EventLevel.LogAlways);

            if (!String.IsNullOrEmpty(parms.WorkingDirectory))
            {
                ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory = parms.WorkingDirectory;
            }
            var rootPath = ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory;

            // Load debug targets
            Console.WriteLine("Loading debuggees...");
            if (parms.Sources != null)
            {
                foreach (var rf in parms.Sources)
                {
                    var f = rf.Replace("~", rootPath);
                    if (!File.Exists(f))
                    {
                        Console.Error.WriteLine("Can't find file {0}", f);
                    }
                    else
                    {
                        this.Add(f);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// BRE debugger
        /// </summary>
        /// <param name="sources"></param>
        public BreDebugger(DebuggerParameters parms) : base(parms.WorkingDirectory)
        {
            this.m_parms = parms;
            Console.WriteLine("Starting debugger...");
            DebugApplicationContext.Start(parms);
            ApplicationServiceContext.Current = ApplicationContext.Current;
            ApplicationServiceContext.Current.GetService <IServiceManager>().AddServiceProvider(typeof(FileSystemResolver));
            Tracer.AddWriter(new ConsoleTraceWriter(EventLevel.LogAlways, "dbg", null), EventLevel.LogAlways);

            if (!String.IsNullOrEmpty(parms.WorkingDirectory))
            {
                ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory = parms.WorkingDirectory;
            }
            var rootPath = ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory;

            // Load debug targets
            Console.WriteLine("Loading debuggees...");

            JavascriptExecutorPool.Current.ExecuteGlobal(o => o.Engine.Step += JreStep);
            JavascriptExecutorPool.Current.ExecuteGlobal(j => j.AddExposedObject("SanteDBDcg", new DisconnectedGatewayJni()));

            if (parms.Sources != null)
            {
                foreach (var rf in parms.Sources)
                {
                    var f = rf.Replace("~", rootPath);
                    if (!File.Exists(f))
                    {
                        Console.Error.WriteLine("Can't find file {0}", f);
                    }
                    else
                    {
                        this.Execute(f);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Main program entry point
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine("SanteDB Administration & Security Console v{0} ({1})", typeof(Program).Assembly.GetName().Version, typeof(Program).Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>()?.InformationalVersion);
            Console.WriteLine("Copyright (C) 2015 - 2020, SanteSuite Community Partners (see NOTICES)");

            var pp      = new ParameterParser <ConsoleParameters>();
            var options = pp.Parse(args);

            if (options.Help)
            {
                pp.WriteHelp(Console.Out);
            }
            else
            {
                try
                {
                    // Add a console trace output
                    if (!String.IsNullOrEmpty(options.Verbosity))
                    {
                        Tracer.AddWriter(new Shell.ConsoleTraceWriter(options.Verbosity), (EventLevel)Enum.Parse(typeof(EventLevel), options.Verbosity));
                    }
                    else
                    {
                        Tracer.AddWriter(new Shell.ConsoleTraceWriter("Error"), EventLevel.Error);
                    }

                    ApplicationContext.Initialize(options);
                    if (ApplicationContext.Current.Start())
                    {
                        new InteractiveShell().Exec();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("FATAL: {0}", e);
                }
            }
Ejemplo n.º 8
0
        /// <summary>
        /// BRE debugger
        /// </summary>
        /// <param name="sources"></param>
        public BreDebugger(StringCollection sources, String rootPath) : base(rootPath)
        {
            ApplicationContext.Current.AddServiceProvider(typeof(FileConfigurationService));


            ApplicationServiceContext.Current = ApplicationContext.Current;
            ApplicationContext.Current.AddServiceProvider(typeof(FileSystemResolver));
            ApplicationContext.Current.AddServiceProvider(typeof(ServiceManager));
            Tracer.AddWriter(new ConsoleTraceWriter(EventLevel.LogAlways, "dbg"), EventLevel.LogAlways);
            ApplicationContext.Current.Start();

            if (!String.IsNullOrEmpty(rootPath))
            {
                ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory = rootPath;
            }
            rootPath = ApplicationContext.Current.GetService <FileSystemResolver>().RootDirectory;

            // Load debug targets
            Console.WriteLine("Loading debuggees...");
            if (sources != null)
            {
                foreach (var rf in sources)
                {
                    var f = rf.Replace("~", rootPath);
                    if (!File.Exists(f))
                    {
                        Console.Error.WriteLine("Can't find file {0}", f);
                    }
                    else
                    {
                        this.Execute(f);
                    }
                }
            }
            JavascriptBusinessRulesEngine.Current.Engine.Step += JreStep;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Start a restore context
        /// </summary>
        /// <returns></returns>
        public static bool StartRestore(IDialogProvider dialogProvider, String instanceName, SecurityApplication applicationId, SanteDBHostType hostType)
        {
            try
            {
                var retVal = new DcApplicationContext(dialogProvider, instanceName, applicationId, hostType);
                retVal.SetProgress("Start restore", 0);
                //retVal.AddServiceProvider(typeof(ConfigurationManager));

                ApplicationServiceContext.Current = DcApplicationContext.Current = retVal;
                retVal.m_tracer = Tracer.GetTracer(typeof(DcApplicationContext));
                var configuration = retVal.Configuration.GetSection <DiagnosticsConfigurationSection>();
                foreach (var tr in configuration.TraceWriter)
                {
                    Tracer.AddWriter(Activator.CreateInstance(tr.TraceWriter, tr.Filter, tr.InitializationData, configuration.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, tr.Filter);
                }
                retVal.GetService <IServiceManager>().AddServiceProvider(typeof(DefaultBackupService));
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("SanteDB FATAL: {0}", e.ToString());
                return(false);
            }
        }
        /// <summary>
        /// Start the application context
        /// </summary>
        public bool Start()
        {
            if (!this.IsRunning)
            {
                Stopwatch startWatch = new Stopwatch();

                using (AuthenticationContext.EnterSystemContext())
                {
                    try
                    {
                        startWatch.Start();

                        if (this.Starting != null)
                        {
                            this.Starting(this, null);
                        }

                        // If there is no configuration manager then add the local
                        Trace.TraceInformation("STAGE0 START: Load Configuration");

                        // Assign diagnostics
                        var config = this.GetService <IConfigurationManager>().GetSection <DiagnosticsConfigurationSection>();

                        if (config != null)
                        {
                            foreach (var writer in config.TraceWriter)
                            {
                                Tracer.AddWriter(Activator.CreateInstance(writer.TraceWriter, writer.Filter, writer.InitializationData, config.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, writer.Filter);
                            }
                        }
#if DEBUG
                        else
                        {
                            Tracer.AddWriter(new SanteDB.Core.Diagnostics.Tracing.SystemDiagnosticsTraceWriter(), System.Diagnostics.Tracing.EventLevel.LogAlways);
                        }
#endif

                        Trace.TraceInformation("STAGE1 START: Start Dependency Injection Manager");
                        this.m_serviceProvider.AddServiceProvider(this);
                        this.m_serviceProvider.Start();

                        Trace.TraceInformation("STAGE2 START: Notify start");
                        this.Started?.Invoke(this, EventArgs.Empty);
                        this.StartTime = DateTime.Now;

                        Trace.TraceInformation("SanteDB startup completed successfully in {0} ms...", startWatch.ElapsedMilliseconds);
                    }
                    catch (Exception e)
                    {
                        m_tracer.TraceError("Error starting up context: {0}", e);
                        this.IsRunning = false;
                        Trace.TraceWarning("Server is running in Maintenance Mode due to error {0}...", e.Message);
                    }
                    finally
                    {
                        AuditUtil.AuditApplicationStartStop(EventTypeCodes.ApplicationStart);
                        startWatch.Stop();
                    }
                }
                this.IsRunning = true;
            }
            return(true);
        }
Ejemplo n.º 11
0
 public frmMain()
 {
     Tracer.AddWriter(new FormTraceWriter(this), EventLevel.LogAlways);
     InitializeComponent();
     this.PopulateConfiguration();
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Start the application context
        /// </summary>
        public static bool Start(ConsoleParameters consoleParms)
        {
            var retVal = new MiniApplicationContext(consoleParms.InstanceName);

            // Not configured
            if (!retVal.ConfigurationPersister.IsConfigured)
            {
                return(false);
            }
            else
            { // load configuration
                try
                {
                    // Set master application context
                    ApplicationServiceContext.Current = ApplicationContext.Current = retVal;
                    retVal.ConfigurationPersister.Backup(retVal.Configuration);

                    retVal.GetService <IServiceManager>().AddServiceProvider(typeof(DefaultBackupService));
                    retVal.GetService <IBackupService>().AutoRestore();

                    retVal.m_tracer = Tracer.GetTracer(typeof(MiniApplicationContext));
                    var configuration = retVal.Configuration.GetSection <DiagnosticsConfigurationSection>();
                    foreach (var tr in configuration.TraceWriter)
                    {
                        Tracer.AddWriter(Activator.CreateInstance(tr.TraceWriter, tr.Filter, tr.InitializationData, configuration.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, tr.Filter);
                    }
                    var appService = retVal.GetService <IAppletManagerService>();

                    retVal.SetProgress("Loading configuration", 0.2f);

                    if (consoleParms.References != null)
                    {
                        MiniApplicationContext.LoadReferences(retVal, consoleParms.References);
                    }

                    // Does openiz.js exist as an asset?
                    var oizJs = appService.Applets.ResolveAsset("/org.santedb.core/js/santedb.js");

                    // Load all solution manifests and attempt to find their pathspec
                    if (!String.IsNullOrEmpty(consoleParms.SolutionFile))
                    {
                        LoadSolution(consoleParms.SolutionFile, appService);
                    }


                    // Load all user-downloaded applets in the data directory
                    if (consoleParms.AppletDirectories != null)
                    {
                        LoadApplets(consoleParms.AppletDirectories.OfType <String>(), appService);
                    }


                    if (oizJs?.Content != null)
                    {
                        byte[] content  = appService.Applets.RenderAssetContent(oizJs);
                        var    oizJsStr = Encoding.UTF8.GetString(content, 0, content.Length);
                        oizJs.Content = oizJsStr + (appService as MiniAppletManagerService).GetShimMethods();
                    }

                    // Set the entity source
                    EntitySource.Current = new EntitySource(retVal.GetService <IEntitySourceProvider>());

                    // Ensure data migration exists
                    var hasDatabase = retVal.ConfigurationManager.Configuration.GetSection <DcDataConfigurationSection>().ConnectionString.Count > 0;
                    try
                    {
                        // If the DB File doesn't exist we have to clear the migrations
                        if (hasDatabase && !File.Exists(retVal.ConfigurationManager.GetConnectionString(retVal.Configuration.GetSection <DcDataConfigurationSection>().MainDataSourceConnectionStringName).GetComponent("dbfile")))
                        {
                            retVal.m_tracer.TraceWarning("Can't find the SanteDB database, will re-install all migrations");
                            retVal.Configuration.GetSection <DcDataConfigurationSection>().MigrationLog.Entry.Clear();
                        }
                        retVal.SetProgress("Migrating databases", 0.6f);

                        ConfigurationMigrator migrator = new ConfigurationMigrator();
                        migrator.Ensure(hasDatabase);

                        // Prepare clinical protocols
                        //retVal.GetService<ICarePlanService>().Repository = retVal.GetService<IClinicalProtocolRepositoryService>();
                    }
                    catch (Exception e)
                    {
                        retVal.m_tracer.TraceError(e.ToString());
                        throw;
                    }
                    finally
                    {
                        retVal.ConfigurationPersister.Save(retVal.Configuration);
                    }


                    if (!retVal.Configuration.GetSection <DiagnosticsConfigurationSection>().TraceWriter.Any(o => o.TraceWriterClassXml.Contains("Console")))
                    {
                        retVal.Configuration.GetSection <DiagnosticsConfigurationSection>().TraceWriter.Add(new TraceWriterConfiguration()
                        {
                            TraceWriter = typeof(ConsoleTraceWriter),
#if DEBUG
                            Filter = EventLevel.Informational
#else
                            Filter = EventLevel.Warning
#endif
                        });
                    }



                    // Start daemons
                    retVal.GetService <IThreadPoolService>().QueueUserWorkItem((o) => retVal.Start());
                }
Ejemplo n.º 13
0
        /// <summary>
        /// Starts the application context using in-memory default configuration for the purposes of
        /// configuring the software
        /// </summary>
        /// <returns><c>true</c>, if temporary was started, <c>false</c> otherwise.</returns>
        public static bool StartTemporary(ConsoleParameters consoleParms)
        {
            try
            {
                // Is autoconfiguration enabled on this
                var retVal = new MiniApplicationContext(consoleParms.InstanceName);
                retVal.SetProgress("Run setup", 0);

                ApplicationServiceContext.Current = ApplicationContext.Current = retVal;


                retVal.m_tracer = Tracer.GetTracer(typeof(MiniApplicationContext));
                var configuration = retVal.Configuration.GetSection <DiagnosticsConfigurationSection>();

                foreach (var tr in configuration.TraceWriter)
                {
                    Tracer.AddWriter(Activator.CreateInstance(tr.TraceWriter, tr.Filter, tr.InitializationData, configuration.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, tr.Filter);
                }

                retVal.SetProgress("Loading configuration", 0.2f);
                var appService = retVal.GetService <IAppletManagerService>();

                if (consoleParms.References != null)
                {
                    MiniApplicationContext.LoadReferences(retVal, consoleParms.References);
                }

                // Does openiz.js exist as an asset?
                var oizJs = appService.Applets.ResolveAsset("/org.santedb.core/js/santedb.js");

                // Load all solution manifests and attempt to find their pathspec
                if (!String.IsNullOrEmpty(consoleParms.SolutionFile))
                {
                    LoadSolution(consoleParms.SolutionFile, appService);
                }


                // Load all user-downloaded applets in the data directory
                if (consoleParms.AppletDirectories != null)
                {
                    LoadApplets(consoleParms.AppletDirectories.OfType <String>(), appService);
                }

                if (oizJs?.Content != null)
                {
                    byte[] content  = appService.Applets.RenderAssetContent(oizJs);
                    var    oizJsStr = Encoding.UTF8.GetString(content, 0, content.Length);
                    oizJs.Content = oizJsStr + (appService as MiniAppletManagerService).GetShimMethods();
                }

                if (!consoleParms.Restore)
                {
                    retVal.GetService <IThreadPoolService>().QueueUserWorkItem((o) => retVal.Start());
                }

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("SanteDB FATAL: {0}", e.ToString());
                return(false);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main(String[] args)
        {
            // Output main header
            var parser = new ParameterParser <ConsoleParameters>();
            var parms  = parser.Parse(args);

            parms.InstanceName = String.IsNullOrEmpty(parms.InstanceName) ? "default" : parms.InstanceName;

            // Output copyright info
            var entryAsm = Assembly.GetEntryAssembly();

            Console.WriteLine("SanteDB Disconnected Server (SanteDB) {0} ({1})", entryAsm.GetName().Version, entryAsm.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion);
            Console.WriteLine("{0}", entryAsm.GetCustomAttribute <AssemblyCopyrightAttribute>().Copyright);
            Console.WriteLine("Complete Copyright information available at http://github.com/santedb/santedb-www");

            // Parameters to force load?
            if (parms.Force)
            {
                foreach (var itm in Directory.GetFiles(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "*.dll"))
                {
                    try
                    {
                        var asm = Assembly.LoadFile(itm);
                        Console.WriteLine("Force Loaded {0}", asm.FullName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERR: Cannot load {0} due to {1}", itm, e.Message);
                    }
                }
            }

            AppDomain.CurrentDomain.AssemblyResolve += (o, e) =>
            {
                string pAsmName = e.Name;
                if (pAsmName.Contains(","))
                {
                    pAsmName = pAsmName.Substring(0, pAsmName.IndexOf(","));
                }

                var asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => e.Name == a.FullName) ??
                          AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => pAsmName == a.GetName().Name);
                return(asm);
            };

            try
            {
                // Detect platform
                if (System.Environment.OSVersion.Platform != PlatformID.Win32NT)
                {
                    Trace.TraceWarning("Not running on WindowsNT, some features may not function correctly");
                }
                else if (!EventLog.SourceExists("SanteDB"))
                {
                    EventLog.CreateEventSource("SanteDB", "santedb-www");
                }

                // Security Application Information
                var applicationIdentity = new SecurityApplication()
                {
                    Key = Guid.Parse("a0d2e3c5-a2d3-11ea-ad9f-00155d4f0905"),
                    ApplicationSecret = parms.ApplicationSecret ?? "SDB$$DEFAULT$$APPSECRET",
                    Name = parms.ApplicationName ?? "org.santedb.disconnected_client"
                };

                // Setup basic parameters
                String[] directory =
                {
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),      "SanteDBWWW", parms.InstanceName),
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SanteDBWWW", parms.InstanceName)
                };

                foreach (var dir in directory)
                {
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                }

                // Token validator
                TokenValidationManager.SymmetricKeyValidationCallback += (o, k, i) =>
                {
                    Trace.TraceError("Trust issuer {0} failed", i);
                    return(false);
                };
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, error) =>
                {
                    if (certificate == null || chain == null)
                    {
                        return(false);
                    }
                    else
                    {
                        if (chain.ChainStatus.Length > 0 || error != SslPolicyErrors.None)
                        {
                            Trace.TraceWarning("The remote certificate is not trusted. The error was {0}. The certificate is: \r\n{1}", error, certificate.Subject);
                            return(false);
                        }
                        return(true);
                    }
                };

                if (parms.ShowHelp)
                {
                    parser.WriteHelp(Console.Out);
                }
                else if (parms.Reset)
                {
                    var appData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SanteDB", parms.InstanceName);
                    var cData   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SanteDB", parms.InstanceName);
                    if (Directory.Exists(appData))
                    {
                        Directory.Delete(cData, true);
                    }
                    if (Directory.Exists(appData))
                    {
                        Directory.Delete(appData, true);
                    }
                    Console.WriteLine("Environment Reset Successful");
                    return;
                }
                else if (parms.ConsoleMode)
                {
#if DEBUG
                    Tracer.AddWriter(new LogTraceWriter(System.Diagnostics.Tracing.EventLevel.LogAlways, "SanteDB.data", new Dictionary <String, EventLevel>()), System.Diagnostics.Tracing.EventLevel.LogAlways);
#else
                    Tracer.AddWriter(new LogTraceWriter(System.Diagnostics.Tracing.EventLevel.Informational, "SanteDB.data", new Dictionary <String, EventLevel>()), System.Diagnostics.Tracing.EventLevel.LogAlways);
#endif
                    Trace.Listeners.Add(new ConsoleTraceListener());
                    ApplicationContext.ProgressChanged += (o, e) =>
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine(">>> PROGRESS >>> {0} : {1:#0%}", e.ProgressText, e.Progress);
                        Console.ResetColor();
                    };

                    if (!DcApplicationContext.StartContext(new ConsoleDialogProvider(), $"www-{parms.InstanceName}", applicationIdentity, SanteDB.Core.SanteDBHostType.Other))
                    {
                        DcApplicationContext.StartTemporary(new ConsoleDialogProvider(), $"www-{parms.InstanceName}", applicationIdentity, SanteDB.Core.SanteDBHostType.Configuration);
                    }

                    DcApplicationContext.Current.Configuration.GetSection <ApplicationServiceContextConfigurationSection>()?.AppSettings?.RemoveAll(o => o.Key == "http.bypassMagic");
                    DcApplicationContext.Current.Configuration.GetSection <ApplicationServiceContextConfigurationSection>()?.AppSettings?.Add(new AppSettingKeyValuePair()
                    {
                        Key = "http.bypassMagic", Value = DcApplicationContext.Current.ExecutionUuid.ToString()
                    });

                    bool restartService = false;
                    if (!parms.Forever)
                    {
                        Console.WriteLine("Press [Enter] key to close...");
                        Console.ReadLine();
                    }
                    else
                    {
                        Console.WriteLine("Will run in nohup daemon mode...");
                        if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                        {
                            // Wait until cancel key is pressed
                            var mre = new ManualResetEventSlim(false);
                            Console.CancelKeyPress += (o, e) => mre.Set();
                            DcApplicationContext.Current.Stopped += (o, e) => mre.Set();
                            mre.Wait();
                        }
                        else
                        {  // running on unix
                           // Now wait until the service is exiting va SIGTERM or SIGSTOP
                            UnixSignal[] signals = new UnixSignal[]
                            {
                                new UnixSignal(Mono.Unix.Native.Signum.SIGINT),
                                new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
                                new UnixSignal(Mono.Unix.Native.Signum.SIGQUIT),
                                new UnixSignal(Mono.Unix.Native.Signum.SIGHUP)
                            };

                            DcApplicationContext.Current.Stopped += (o, e) =>
                            {
                                Console.WriteLine("Service has stopped, will send SIGHUP to self for restart");
                                restartService = true;
                                Syscall.kill(Syscall.getpid(), Signum.SIGHUP);
                            };

                            Console.WriteLine("Started - Send SIGINT, SIGTERM, SIGQUIT or SIGHUP to PID {0} to terminate", Process.GetCurrentProcess().Id);
                            int signal = UnixSignal.WaitAny(signals);
                        }
                    }

                    Console.WriteLine($"Received termination signal... {DcApplicationContext.Current?.IsRunning}");
                    if (DcApplicationContext.Current?.IsRunning == true && !restartService)
                    {
                        DcApplicationContext.Current.Stop();
                    }
                    else
                    {
                        // Service stopped the context so we want to restart
                        Console.WriteLine("Will restart context, waiting for main teardown in 5 seconds...");
                        var pi = new ProcessStartInfo(typeof(Program).Assembly.Location, string.Join(" ", args));
                        pi.UseShellExecute = true;
                        Process.Start(pi);
                        Environment.Exit(0);
                    }
                }
                else if (parms.Install)
                {
                    string serviceName = $"sdb-www-{parms.InstanceName}";
                    if (!ServiceTools.ServiceInstaller.ServiceIsInstalled(serviceName))
                    {
                        String argList = String.Empty;
                        if (!String.IsNullOrEmpty(parms.ApplicationName))
                        {
                            argList += $" --appname=\"{parms.ApplicationName}\"";
                        }
                        if (!String.IsNullOrEmpty(parms.ApplicationSecret))
                        {
                            argList += $" --appsecret=\"{parms.ApplicationSecret}\"";
                        }

                        ServiceTools.ServiceInstaller.Install(
                            serviceName, $"SanteDB WWW ({parms.InstanceName})",
                            $"{entryAsm.Location} --name=\"{parms.InstanceName}\" {argList}",
                            null, null, ServiceTools.ServiceBootFlag.AutoStart);
                    }
                    else
                    {
                        throw new InvalidOperationException("Service instance already installed");
                    }
                }
                else if (parms.Uninstall)
                {
                    string serviceName = $"sdb-www-{parms.InstanceName}";
                    if (ServiceTools.ServiceInstaller.ServiceIsInstalled(serviceName))
                    {
                        ServiceTools.ServiceInstaller.Uninstall(serviceName);
                    }
                    else
                    {
                        throw new InvalidOperationException("Service instance not installed");
                    }
                }
                else if (parms.Restart)
                {
                    string serviceName = $"sdb-www-{parms.InstanceName}";
                    if (ServiceTools.ServiceInstaller.ServiceIsInstalled(serviceName))
                    {
                        Console.Write("Stopping {0}...", serviceName);
                        var niter = 0;
                        ServiceTools.ServiceInstaller.StopService(serviceName);
                        while (ServiceTools.ServiceInstaller.GetServiceStatus(serviceName) != ServiceTools.ServiceState.Stop && niter < 10)
                        {
                            Thread.Sleep(1000);
                            Console.Write(".");
                            niter++;
                        }
                        Console.Write("\r\nStarting {0}...", serviceName);
                        ServiceTools.ServiceInstaller.StartService(serviceName);
                        while (ServiceTools.ServiceInstaller.GetServiceStatus(serviceName) != ServiceTools.ServiceState.Run && niter < 20)
                        {
                            Thread.Sleep(1000);
                            Console.Write(".");
                            niter++;
                        }
                        Console.WriteLine("Restart Complete");
                    }
                }
                else
                {
                    Trace.TraceInformation("Starting as Windows Service");
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[]
                    {
                        new SanteDbService(parms.InstanceName, applicationIdentity)
                    };
                    ServiceBase.Run(ServicesToRun);
                    Trace.TraceInformation("Started As Windows Service...");
                }
            }
            catch (Exception e)
            {
#if DEBUG
                Trace.TraceError("011 899 981 199 911 9725 3!!! {0}", e.ToString());
                Console.WriteLine("011 899 981 199 911 9725 3!!! {0}", e.ToString());
#else
                Trace.TraceError("Error encountered: {0}. Will terminate", e);
                EventLog.WriteEntry("SanteDB", $"Fatal service error: {e}", EventLogEntryType.Error, 911);
                Console.WriteLine("FATAL ERROR: {0}", e);
#endif
                Environment.Exit(911);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Start the application context
        /// </summary>
        public static bool StartContext(IDialogProvider dialogProvider, String instanceName, SecurityApplication applicationId, SanteDBHostType hostType)
        {
            // Not configured
            if (!new DcConfigurationManager(instanceName).IsConfigured)
            {
                return(false);
            }
            else
            {
                // Set master application context
                DcApplicationContext retVal = null;
                try
                {
                    try
                    {
                        retVal = new DcApplicationContext(dialogProvider, instanceName, applicationId, hostType);
                        ApplicationServiceContext.Current = DcApplicationContext.Current = retVal;
                        //retVal.AddServiceProvider(typeof(ConfigurationManager));
                        if (retVal.ConfigurationPersister == null)
                        {
                            throw new InvalidOperationException("Missing configuration persistence service");
                        }
                        retVal.ConfigurationPersister.Backup(retVal.Configuration);
                    }
                    catch (Exception e)
                    {
                        Trace.TraceWarning("Error loading configuration: {0}", e);
                        if (retVal.ConfigurationPersister.HasBackup() && retVal.Confirm(Strings.err_configuration_invalid_restore_prompt))
                        {
                            retVal.ConfigurationPersister.Restore();
                            retVal.ConfigurationManager.Reload();
                        }
                        else
                        {
                            throw new Exception("Could not load or backup configuration", e);
                        }
                    }

                    if (retVal.GetService <IBackupService>() == null)
                    {
                        retVal.GetService <IServiceManager>().AddServiceProvider(typeof(DefaultBackupService));
                    }

                    // Is there a backup, and if so, does the user want to restore from that backup?
                    var backupSvc = retVal.GetService <IBackupService>();
                    if (retVal.ConfigurationManager.GetAppSetting("ignore.restore") == null &&
                        backupSvc.HasBackup(BackupMedia.Public) &&
                        retVal.Confirm(Strings.locale_confirm_restore))
                    {
                        backupSvc.Restore(BackupMedia.Public);
                    }
                    else
                    {
                        backupSvc.AutoRestore();
                    }

                    // Ignore restoration
                    if (retVal.ConfigurationManager.GetAppSetting("ignore.restore") == null)
                    {
                        retVal.Configuration.GetSection <ApplicationServiceContextConfigurationSection>().AppSettings.Add(new AppSettingKeyValuePair()
                        {
                            Key   = "ignore.restore",
                            Value = "true"
                        });
                    }

                    // Add tracers
                    retVal.m_tracer = Tracer.GetTracer(typeof(DcApplicationContext));
                    retVal.m_tracer.TraceInfo("Starting logging infrastructure");
                    var configuration = retVal.Configuration.GetSection <DiagnosticsConfigurationSection>();
                    foreach (var tr in configuration.TraceWriter)
                    {
                        Tracer.AddWriter(Activator.CreateInstance(tr.TraceWriter, tr.Filter, tr.InitializationData, configuration.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, tr.Filter);
                    }

                    retVal.SetProgress("Loading configuration", 0.2f);

                    // Load all user-downloaded applets in the data directory
                    var configuredApplets = retVal.Configuration.GetSection <AppletConfigurationSection>().Applets;

                    var appletService = retVal.GetService <IAppletManagerService>();
                    var updateService = retVal.GetService <IUpdateManager>();

                    foreach (var appletInfo in configuredApplets.ToArray())// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
                    {
                        try
                        {
                            retVal.m_tracer.TraceInfo("Loading applet {0}", appletInfo);
                            String appletPath = Path.Combine(retVal.Configuration.GetSection <AppletConfigurationSection>().AppletDirectory, appletInfo.Id);
                            using (var fs = File.OpenRead(appletPath))
                            {
                                AppletManifest manifest = AppletManifest.Load(fs);
                                // Is this applet in the allowed applets

                                // public key token match?
                                if (appletInfo.PublicKeyToken != manifest.Info.PublicKeyToken)
                                {
                                    retVal.m_tracer.TraceWarning("Applet {0} failed validation", appletInfo);
                                    ; // TODO: Raise an error
                                }

                                appletService.LoadApplet(manifest);
                            }
                        }
                        catch (Exception e)
                        {
                            if (retVal.Confirm(String.Format(Strings.err_applet_corrupt_reinstall, appletInfo.Id)))
                            {
                                String appletPath = Path.Combine(retVal.Configuration.GetSection <AppletConfigurationSection>().AppletDirectory, appletInfo.Id);
                                if (File.Exists(appletPath))
                                {
                                    File.Delete(appletPath);
                                }
                                try
                                {
                                    configuredApplets.Remove(appletInfo);
                                    updateService.Install(appletInfo.Id);
                                }
                                catch
                                {
                                    retVal.Alert(String.Format(Strings.err_updateFailed));
                                }
                            }
                            else
                            {
                                retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appletInfo, e.ToString());
                                throw new Exception($"Could not load applet {appletInfo}", e);
                            }
                        }
                    }

                    // Set the entity source
                    EntitySource.Current = new EntitySource(retVal.GetService <IEntitySourceProvider>());
                    ApplicationServiceContext.Current = ApplicationContext.Current;

                    // Ensure data migration exists
                    bool hasDatabase = retVal.ConfigurationManager.Configuration.GetSection <DcDataConfigurationSection>().ConnectionString.Count > 0;
                    try
                    {
                        // If the DB File doesn't exist we have to clear the migrations
                        if (hasDatabase && !File.Exists(retVal.ConfigurationManager.GetConnectionString(retVal.Configuration.GetSection <DcDataConfigurationSection>().MainDataSourceConnectionStringName).GetComponent("dbfile")))
                        {
                            retVal.m_tracer.TraceWarning("Can't find the SanteDB database, will re-install all migrations");
                            retVal.Configuration.GetSection <DcDataConfigurationSection>().MigrationLog.Entry.Clear();
                        }
                        retVal.SetProgress("Migrating databases", 0.6f);

                        ConfigurationMigrator migrator = new ConfigurationMigrator();
                        migrator.Ensure(hasDatabase);


                        // Prepare clinical protocols
                        //retVal.GetService<ICarePlanService>().Repository = retVal.GetService<IClinicalProtocolRepositoryService>();
                    }
                    catch (Exception e)
                    {
                        retVal.m_tracer.TraceError(e.ToString());
                        throw new Exception("Error executing migrations", e);
                    }
                    finally
                    {
                        retVal.ConfigurationPersister.Save(retVal.Configuration);
                    }

                    // Update the applets if there are new versions
                    foreach (var appPath in Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "applets")))
                    {
                        try
                        {
                            using (var fs = File.OpenRead(appPath))
                            {
                                retVal.m_tracer.TraceInfo("Checking if {0} is upgradable", appPath);
                                AppletPackage package  = AppletPackage.Load(fs);
                                var           existing = appletService.GetApplet(package.Meta.Id);
                                retVal.m_tracer.TraceInfo("{0} = {1} , existing = {2}", appPath, package.Meta, existing?.Info);

                                if (existing == null || new Version(existing.Info.Version) < new Version(package.Meta.Version))
                                {
                                    if (existing != null)
                                    {
                                        retVal.m_tracer.TraceInfo("Upgrading applet {0} from {1} to {2}", package.Meta.Id, existing.Info.Version, package.Meta.Version);
                                    }
                                    appletService.Install(package, true);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            retVal.m_tracer.TraceError("Checking upgrade for applet {0} failed: {1}", appPath, e.ToString());
                        }
                    }

                    if (retVal.GetService <IThreadPoolService>() == null)
                    {
                        throw new InvalidOperationException(("Missing thread pool service(s)"));
                    }
                    // Start daemons
                    updateService?.AutoUpdate();
                    retVal.GetService <IThreadPoolService>().QueueUserWorkItem((o) => retVal.Start());

                    //retVal.Start();
                }
                catch (Exception e)
                {
                    //ApplicationContext.Current = null;
                    throw new Exception("Error starting context", e);
                }
                return(true);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Start the application context
        /// </summary>
        public bool Start()
        {
            if (!this.m_running)
            {
                Stopwatch startWatch = new Stopwatch();

                try
                {
                    startWatch.Start();

                    if (this.Starting != null)
                    {
                        this.Starting(this, null);
                    }

                    // If there is no configuration manager then add the local
                    Trace.TraceInformation("STAGE0 START: Load Configuration");

                    if (this.GetService <IConfigurationManager>() == null)
                    {
                        throw new InvalidOperationException("Cannot find configuration manager!");
                    }

                    this.m_configuration = this.GetService <IConfigurationManager>().GetSection <ApplicationServiceContextConfigurationSection>();

                    if (this.m_configuration == null)
                    {
                        throw new InvalidOperationException("Cannot load configuration, perhaps the services aren't installed?");
                    }

                    // Assign diagnostics
                    var config = this.GetService <IConfigurationManager>().GetSection <DiagnosticsConfigurationSection>();

                    if (config != null)
                    {
                        foreach (var writer in config.TraceWriter)
                        {
                            Tracer.AddWriter(Activator.CreateInstance(writer.TraceWriter, writer.Filter, writer.InitializationData) as TraceWriter, writer.Filter);
                        }
                    }
#if DEBUG
                    else
                    {
                        Tracer.AddWriter(new SystemDiagnosticsTraceWriter(), System.Diagnostics.Tracing.EventLevel.LogAlways);
                    }
#endif
                    // Add this
                    this.m_serviceInstances.Add(this);
                    Trace.TraceInformation("STAGE1 START: Loading services");

                    foreach (var svc in this.m_configuration.ServiceProviders)
                    {
                        if (svc.Type == null)
                        {
                            Trace.TraceWarning("Cannot find service {0}, skipping", svc.TypeXml);
                        }
                        else
                        {
                            Trace.TraceInformation("Creating {0}...", svc.Type);
                            var instance = Activator.CreateInstance(svc.Type);
                            this.m_serviceInstances.Add(instance);
                        }
                    }

                    Trace.TraceInformation("STAGE2 START: Starting Daemons");
                    foreach (var dc in this.m_serviceInstances.OfType <IDaemonService>().ToArray())
                    {
                        if (!dc.Start())
                        {
                            throw new Exception($"Service {dc} reported unsuccessful start");
                        }
                    }

                    Trace.TraceInformation("STAGE3 START: Notify ApplicationContext has started");
                    if (this.Started != null)
                    {
                        this.Started(this, null);
                    }

                    this.StartTime = DateTime.Now;

                    AuditUtil.AuditApplicationStartStop(EventTypeCodes.ApplicationStart);
                }
                finally
                {
                    startWatch.Stop();
                }
                Trace.TraceInformation("SanteDB startup completed successfully in {0} ms...", startWatch.ElapsedMilliseconds);
                this.m_running = true;
            }

            return(true);
        }