Пример #1
0
 /// <summary>
 /// Install the specified package
 /// </summary>
 public void Install(string packageId)
 {
     try
     {
         if (ApplicationContext.Current.GetService <INetworkInformationService>().IsNetworkAvailable)
         {
             var amiClient = new AmiServiceClient(ApplicationContext.Current.GetRestClient("ami"));
             amiClient.Client.Credentials      = this.GetCredentials(amiClient.Client);
             amiClient.Client.ProgressChanged += (o, e) => ApplicationContext.Current.SetProgress(String.Format(Strings.locale_downloading, packageId), e.Progress);
             amiClient.Client.Description.Endpoint[0].Timeout = 30000;
             // Fetch the applet package
             using (var ms = amiClient.DownloadApplet(packageId))
             {
                 var package = AppletPackage.Load(ms);
                 this.m_tracer.TraceInfo("Upgrading {0}...", package.Meta.ToString());
                 ApplicationContext.Current.GetService <IAppletManagerService>().Install(package, true);
                 // ApplicationContext.Current.Exit(); // restart
             }
         }
         else
         {
             return;
         }
     }
     catch (Exception ex)
     {
         this.m_tracer.TraceError("Error contacting AMI: {0}", ex.Message);
         throw new InvalidOperationException(Strings.err_updateFailed);
     }
 }
        public object Create(object data, bool updateIfExists)
        {
            var pkg = AppletPackage.Load((Stream)data);

            ApplicationServiceContext.Current.GetService <IAppletManagerService>().Install(pkg);
            X509Certificate2 cert = null;

            if (pkg.PublicKey != null)
            {
                cert = new X509Certificate2(pkg.PublicKey);
            }
            else if (pkg.Meta.PublicKeyToken != null)
            {
                X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                try
                {
                    store.Open(OpenFlags.ReadOnly);
                    var results = store.Certificates.Find(X509FindType.FindByThumbprint, pkg.Meta.PublicKeyToken, false);
                    if (results.Count > 0)
                    {
                        cert = results[0];
                    }
                }
                finally
                {
                    store.Close();
                }
            }
            return(new AppletManifestInfo(pkg.Meta, new X509Certificate2Info(cert?.Issuer, cert?.NotBefore, cert?.NotAfter, cert?.Subject, cert?.Thumbprint)));
        }
Пример #3
0
        /// <summary>
        /// Starts the daemon service
        /// </summary>
        public bool Start()
        {
            this.m_tracer.TraceInformation("Starting applet manager service...");

            this.Starting?.Invoke(this, EventArgs.Empty);

            try
            {
                // Load packages from applets/ filesystem directory
                var appletDir = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "applets");
                if (!Directory.Exists(appletDir))
                {
                    this.m_tracer.TraceWarning("Applet directory {0} doesn't exist, no applets will be loaded", appletDir);
                }
                else
                {
                    this.m_tracer.TraceEvent(TraceEventType.Verbose, 0, "Scanning {0} for applets...", appletDir);
                    foreach (var f in Directory.GetFiles(appletDir))
                    {
                        // Try to open the file
                        this.m_tracer.TraceInformation("Loading {0}...", f);
                        using (var fs = File.OpenRead(f))
                        {
                            var pkg = AppletPackage.Load(fs);

                            if (this.m_fileDictionary.ContainsKey(pkg.Meta.Id))
                            {
                                this.m_tracer.TraceEvent(TraceEventType.Critical, 1096, "Duplicate package {0} is not permitted", pkg.Meta.Id);
                                throw new DuplicateKeyException(pkg.Meta.Id);
                            }
                            else if (this.Install(pkg, true))
                            {
                                //this.m_appletCollection.Add(pkg.Unpack());
                                //this.m_fileDictionary.Add(pkg.Meta.Id, f);
                            }
                            else
                            {
                                this.m_tracer.TraceEvent(TraceEventType.Critical, 1098, "Cannot proceed while untrusted applets are present");
                                throw new SecurityException("Cannot proceed while untrusted applets are present");
                            }
                        }
                    }
                }
            }
            catch (SecurityException e)
            {
                this.m_tracer.TraceEvent(TraceEventType.Error, e.HResult, "Error loading applets: {0}", e);
                throw new InvalidOperationException("Cannot proceed while untrusted applets are present");
            }
            catch (Exception ex)
            {
                this.m_tracer.TraceEvent(TraceEventType.Error, ex.HResult, "Error loading applets: {0}", ex);
                throw;
            }

            this.Started?.Invoke(this, EventArgs.Empty);
            return(true);
        }
Пример #4
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 appContextName = "OpenIZDC")
        {
            try
            {
                var retVal = new DcApplicationContext(dialogProvider);
                retVal.SetProgress("Run setup", 0);

                retVal.m_configurationManager = new DcConfigurationManager(DcConfigurationManager.GetDefaultConfiguration(appContextName), appContextName);

                ApplicationContext.Current         = retVal;
                ApplicationServiceContext.Current  = ApplicationContext.Current;
                ApplicationServiceContext.HostType = OpenIZHostType.OtherClient;
                retVal.ConfigurationManager.Configuration.GetSection <ApplicationConfigurationSection>().AppSettings.RemoveAll(o => o.Key == "http.index");
                retVal.ConfigurationManager.Configuration.GetSection <ApplicationConfigurationSection>().AppSettings.Add(new AppSettingKeyValuePair()
                {
                    Key = "http.index", Value = "/org.openiz.core/views/settings/index.html"
                });

                retVal.m_tracer = Tracer.GetTracer(typeof(DcApplicationContext));
                retVal.ThreadDefaultPrincipal = AuthenticationContext.SystemPrincipal;

                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.Start();

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("OpenIZ FATAL: {0}", e.ToString());
                return(false);
            }
        }
Пример #5
0
        /// <summary>
        /// Install the specified package
        /// </summary>
        public void Install(string packageId)
        {
            try
            {
                if (ApplicationContext.Current.GetService <INetworkInformationService>().IsNetworkAvailable)
                {
                    var amiClient = new AmiServiceClient(ApplicationContext.Current.GetRestClient("ami"));

                    using (this.Authenticate(amiClient.Client, out Credentials credentials))
                    {
                        amiClient.Client.Credentials      = credentials;
                        amiClient.Client.ProgressChanged += (o, e) => ApplicationContext.Current.SetProgress(string.Format(Strings.locale_downloading, packageId), e.Progress);
                        amiClient.Client.Description.Endpoint[0].Timeout = 30000;

                        // Fetch the applet package
                        if (string.IsNullOrEmpty(this.m_configuration.AppletSolution))
                        {
                            using (var ms = amiClient.DownloadApplet(packageId))
                            {
                                var package = AppletPackage.Load(ms);
                                this.m_tracer.TraceInfo("Upgrading {0}...", package.Meta.ToString());
                                ApplicationContext.Current.GetService <IAppletManagerService>().Install(package, true);
                                ApplicationServiceContext.Current.GetService <ITickleService>().SendTickle(new Tickle(Guid.Empty, TickleType.Information, string.Format(Strings.locale_updateInstalled, package.Meta.Id, package.Meta.Version)));

                                // ApplicationContext.Current.Exit(); // restart
                            }
                        }
                        else
                        {
                            using (var ms = new MemoryStream(amiClient.Client.Get($"AppletSolution/{this.m_configuration.AppletSolution}/applet/{packageId}")))
                            {
                                var package = AppletPackage.Load(ms);
                                this.m_tracer.TraceInfo("Upgrading {0}...", package.Meta.ToString());
                                ApplicationContext.Current.GetService <IAppletManagerService>().Install(package, true);
                                ApplicationServiceContext.Current.GetService <ITickleService>().SendTickle(new Tickle(Guid.Empty, TickleType.Information, string.Format(Strings.locale_updateInstalled, package.Meta.Id, package.Meta.Version)));

                                // ApplicationContext.Current.Exit(); // restart
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.m_tracer.TraceError("Error contacting AMI: {0}", ex.Message);
                throw new InvalidOperationException(Strings.err_updateFailed);
            }
        }
Пример #6
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);
            }
        }
Пример #7
0
        /// <summary>
        /// Downloads the applet.
        /// </summary>
        /// <param name="appletId">The applet identifier.</param>
        /// <returns>Stream.</returns>
        public Stream DownloadApplet(string appletId)
        {
            var appletService = ApplicationContext.Current.GetService <IAppletManagerService>();
            var appletData    = appletService.GetPackage(appletId);

            if (appletData == null)
            {
                throw new FileNotFoundException(appletId);
            }
            else
            {
                var appletManifest = AppletPackage.Load(appletData);
                this.SetAppletHeaders(appletManifest.Meta);
                return(new MemoryStream(appletData));
            }
        }
Пример #8
0
        /// <summary>
        /// Put the application into the file repository
        /// </summary>
        public AppletInfo Put(Stream body)
        {
            var package = AppletPackage.Load(body);

            try
            {
                this.m_configuration.Repository.GetRepository().Get(package.Meta.Id, new Version(package.Meta.Version), true);
                throw new FaultException(409, $"Package {package.Meta.Id} version {package.Meta.Version} already exists");
            }
            catch (KeyNotFoundException)
            {
                return(this.m_configuration.Repository.GetRepository().Put(package));
            }
            finally
            {
            }
        }
Пример #9
0
        public object Update(object data)
        {
            var appletMgr = ApplicationServiceContext.Current.GetService <IAppletSolutionManagerService>();

            var pkg = AppletPackage.Load((Stream)data) as AppletSolution;

            if (!appletMgr.Solutions.Any(o => pkg.Meta.Id == o.Meta.Id))
            {
                this.m_tracer.TraceError($"File not found: {pkg.Meta.Id}");
                throw new FileNotFoundException(this.m_localizationService.FormatString("error.rest.ami.FileNotFoundParam", new
                {
                    param = pkg.Meta.Id
                }));
            }


            appletMgr.Install(pkg, true);
            X509Certificate2 cert = null;

            if (pkg.PublicKey != null)
            {
                cert = new X509Certificate2(pkg.PublicKey);
            }
            else if (pkg.Meta.PublicKeyToken != null)
            {
                X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                try
                {
                    store.Open(OpenFlags.ReadOnly);
                    var results = store.Certificates.Find(X509FindType.FindByThumbprint, pkg.Meta.PublicKeyToken, false);
                    if (results.Count > 0)
                    {
                        cert = results[0];
                    }
                }
                finally
                {
                    store.Close();
                }
            }
            return(new AppletSolutionInfo(pkg, new X509Certificate2Info(cert?.Issuer, cert?.NotBefore, cert?.NotAfter, cert?.Subject, cert?.Thumbprint)));
        }
Пример #10
0
        /// <summary>
        /// Sign an existing package
        /// </summary>
        public int Sign()
        {
            try
            {
                AppletPackage pkg = null;
                using (FileStream fs = File.OpenRead(this.m_parms.Source))
                    pkg = AppletPackage.Load(fs);

                Emit.Message("INFO", "Will sign package {0}", pkg.Meta);
                pkg = this.CreateSignedPackage(pkg.Unpack());
                using (FileStream fs = File.Create(this.m_parms.Output ?? Path.ChangeExtension(this.m_parms.Source, ".signed.pak")))
                    pkg.Save(fs);
                return(0);
            }
            catch (Exception e)
            {
                Emit.Message("ERROR", "Cannot sign package: {0}", e);
                return(-0232);
            }
        }
Пример #11
0
        /// <summary>
        /// Sign an existing package
        /// </summary>
        private static int Sign(ConsoleParameters parameters)
        {
            try
            {
                AppletPackage pkg = null;
                using (FileStream fs = File.OpenRead(parameters.Source))
                    pkg = AppletPackage.Load(fs);

                Console.WriteLine("Will sign package {0}", pkg.Meta);
                pkg = CreateSignedPackage(pkg.Unpack(), parameters);
                using (FileStream fs = File.Create(parameters.Output ?? Path.ChangeExtension(parameters.Source, ".signed.pak")))
                    pkg.Save(fs);
                return(0);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Cannot sign package: {0}", e);
                return(-0232);
            }
        }
        public object Get(Object appletId, Object versionId)
        {
            var appletService = ApplicationServiceContext.Current.GetService <IAppletManagerService>();
            var appletData    = appletService.GetPackage(appletId.ToString());

            if (appletData == null)
            {
                this.m_tracer.TraceError($"File not found: {appletId}");
                throw new FileNotFoundException(this.m_localizationService.FormatString("error.rest.ami.FileNotFoundParam", new
                {
                    param = appletId.ToString()
                }));
            }
            else
            {
                var appletManifest = AppletPackage.Load(appletData);
                this.SetAppletHeaders(appletManifest.Meta);
                return(new MemoryStream(appletData));
            }
        }
Пример #13
0
        /// <summary>
        /// Get the specified package contents
        /// </summary>
        public AppletPackage Get(string id, Version version, bool exactVersion = false)
        {
            // Locate the specified package
            try
            {
                var path = $"pak/{id}";
                if (version != null)
                {
                    path += $"/{version}";
                }

                using (var inStream = this.m_client.Get <MemoryStream>(path))
                    return(AppletPackage.Load(inStream));
            }
            catch (RestClientException e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "Error fetching package {0} v{1}: {2}", id, version, e);
                throw;
            }
        }
Пример #14
0
        /// <summary>
        /// Updates an applet.
        /// </summary>
        /// <param name="appletId">The id of the applet to be updated.</param>
        /// <param name="appletData">The applet containing the updated information.</param>
        /// <returns>Returns the updated applet.</returns>
        /// <exception cref="System.ArgumentException">Applet not found.</exception>
        public AppletManifestInfo UpdateApplet(string appletId, Stream appletData)
        {
            var appletMgr = ApplicationContext.Current.GetService <IAppletManagerService>();

            if (!appletMgr.Applets.Any(o => o.Info.Id == appletId))
            {
                throw new FileNotFoundException(appletId);
            }

            var pkg = AppletPackage.Load(appletData);

            ApplicationContext.Current.GetService <IAppletManagerService>().Install(pkg, true);
            X509Certificate2 cert = null;

            if (pkg.PublicKey != null)
            {
                cert = new X509Certificate2(pkg.PublicKey);
            }
            else if (pkg.Meta.PublicKeyToken != null)
            {
                X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                try
                {
                    store.Open(OpenFlags.ReadOnly);
                    var results = store.Certificates.Find(X509FindType.FindByThumbprint, pkg.Meta.PublicKeyToken, false);
                    if (results.Count > 0)
                    {
                        cert = results[0];
                    }
                }
                finally
                {
                    store.Close();
                }
            }
            return(new AppletManifestInfo(pkg.Meta, new X509Certificate2Info(cert?.Issuer, cert?.NotBefore, cert?.NotAfter, cert?.Subject, cert?.Thumbprint)));
        }
Пример #15
0
        public object Create(object data, bool updateIfExists)
        {
            var pkg = AppletPackage.Load((Stream)data) as AppletSolution;

            if (pkg == null)
            {
                this.m_tracer.TraceError("Package does not appear to be a solution");
                throw new InvalidOperationException(this.m_localizationService.GetString("error.rest.ami.packageNotASolution"));
            }

            ApplicationServiceContext.Current.GetService <IAppletSolutionManagerService>().Install(pkg);
            X509Certificate2 cert = null;

            if (pkg.PublicKey != null)
            {
                cert = new X509Certificate2(pkg.PublicKey);
            }
            else if (pkg.Meta.PublicKeyToken != null)
            {
                X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                try
                {
                    store.Open(OpenFlags.ReadOnly);
                    var results = store.Certificates.Find(X509FindType.FindByThumbprint, pkg.Meta.PublicKeyToken, false);
                    if (results.Count > 0)
                    {
                        cert = results[0];
                    }
                }
                finally
                {
                    store.Close();
                }
            }
            return(new AppletSolutionInfo(pkg, new X509Certificate2Info(cert?.Issuer, cert?.NotBefore, cert?.NotAfter, cert?.Subject, cert?.Thumbprint)));
        }
        /// <summary>
        /// Get specific applet
        /// </summary>
        public object Get(Type scopingType, object scopingKey, object key)
        {
            var appletData = this.m_solutionManager.GetPackage(scopingKey.ToString(), key.ToString());

            if (appletData == null)
            {
                throw new FileNotFoundException(key.ToString());
            }
            else
            {
                var appletManifest = AppletPackage.Load(appletData);
                RestOperationContext.Current.OutgoingResponse.SetETag(appletManifest.Meta.Version);
                RestOperationContext.Current.OutgoingResponse.Headers.Add("X-SanteDB-PakID", appletManifest.Meta.Id);
                if (appletManifest.Meta.Hash != null)
                {
                    RestOperationContext.Current.OutgoingResponse.AppendHeader("X-SanteDB-Hash", Convert.ToBase64String(appletManifest.Meta.Hash));
                }
                RestOperationContext.Current.OutgoingResponse.AppendHeader("Content-Type", "application/octet-stream");
                RestOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
                RestOperationContext.Current.OutgoingResponse.AppendHeader("Content-Disposition", $"attachment; filename=\"{appletManifest.Meta.Id}.pak.gz\"");
                RestOperationContext.Current.OutgoingResponse.AppendHeader("Location", $"/ami/Applet/{appletManifest.Meta.Id}");
                return(new MemoryStream(appletData));
            }
        }
Пример #17
0
        /// <summary>
        /// Start the application context
        /// </summary>
        public static bool Start(A.Content.Context launcherActivity, A.Content.Context context, A.App.Application application)
        {
            var retVal = new AndroidApplicationContext();

            retVal.Context = context;
            retVal.m_configurationManager = new ConfigurationManager();
            retVal.AndroidApplication     = application;

            // Not configured
            if (!retVal.ConfigurationManager.IsConfigured)
            {
                NoConfiguration?.Invoke(null, EventArgs.Empty);
                return(false);
            }
            else
            { // load configuration
                try
                {
                    // Set master application context
                    ApplicationContext.Current = retVal;
                    retVal.CurrentActivity     = launcherActivity;
                    try
                    {
                        retVal.ConfigurationManager.Load();
                        retVal.ConfigurationManager.Backup();
                    }
                    catch
                    {
                        if (retVal.ConfigurationManager.HasBackup() &&
                            retVal.Confirm(Strings.err_configuration_invalid_restore_prompt))
                        {
                            retVal.ConfigurationManager.Restore();
                            retVal.ConfigurationManager.Load();
                        }
                        else
                        {
                            throw;
                        }
                    }

                    retVal.AddServiceProvider(typeof(AndroidBackupService));

                    retVal.m_tracer = Tracer.GetTracer(typeof(AndroidApplicationContext), retVal.ConfigurationManager.Configuration);

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

                    // Ignore restoration
                    if (!retVal.Configuration.GetSection <ApplicationConfigurationSection>().AppSettings.Any(o => o.Key == "ignore.restore"))
                    {
                        retVal.Configuration.GetSection <ApplicationConfigurationSection>().AppSettings.Add(new AppSettingKeyValuePair()
                        {
                            Key   = "ignore.restore",
                            Value = "true"
                        });
                    }

                    // HACK: For some reason the PCL doesn't do this automagically
                    //var connectionString = retVal.Configuration.GetConnectionString("openIzWarehouse");
                    //if (!File.Exists(connectionString.Value))
                    //{
                    //    retVal.m_tracer.TraceInfo("HAX: Creating warehouse file since PCL can't... {0}", connectionString.Value);
                    //    SqliteConnection.CreateFile(connectionString.Value);
                    //}
                    // Load configured applets
                    var configuredApplets = retVal.Configuration.GetSection <AppletConfigurationSection>().Applets;

                    retVal.SetProgress(context.GetString(Resource.String.startup_configuration), 0.2f);
                    var appletManager = retVal.GetService <IAppletManagerService>();

                    // Load all user-downloaded applets in the data directory
                    foreach (var appletInfo in configuredApplets)// 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);

                            if (!File.Exists(appletPath)) // reinstall
                            {
                                retVal.Configuration.GetSection <AppletConfigurationSection>().Applets.Clear();
                                retVal.SaveConfiguration();
                                retVal.Alert(Strings.locale_restartRequired);
                                throw new AppDomainUnloadedException();
                            }

                            // Load
                            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
                                }

                                appletManager.LoadApplet(manifest);
                            }
                        }
                        catch (AppDomainUnloadedException) { throw; }
                    }
                    catch (Exception e)
                    {
                        retVal.m_tracer.TraceError("Applet Load Error: {0}", 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);
                            }
                        }
                        else
                        {
                            retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appletInfo, e.ToString());
                            throw;
                        }
                    }

                    // Are we going to deploy applets
                    // Upgrade applets from our app manifest
                    foreach (var itm in context.Assets.List("Applets"))
                    {
                        try
                        {
                            retVal.m_tracer.TraceVerbose("Loading {0}", itm);
                            AppletPackage pkg = AppletPackage.Load(context.Assets.Open(String.Format("Applets/{0}", itm)));

                            // Write data to assets directory
#if !DEBUG
                            if (appletManager.GetApplet(pkg.Meta.Id) == null || new Version(appletManager.GetApplet(pkg.Meta.Id).Info.Version) < new Version(pkg.Meta.Version))
#endif
                            appletManager.Install(pkg, true);
                        }
                        catch (Exception e)
                        {
                            retVal.m_tracer?.TraceError(e.ToString());
                        }
                    }

                    // Ensure data migration exists
                    try
                    {
                        // If the DB File doesn't exist we have to clear the migrations
                        if (!File.Exists(retVal.Configuration.GetConnectionString(retVal.Configuration.GetSection <DataConfigurationSection>().MainDataSourceConnectionStringName).Value))
                        {
                            retVal.m_tracer.TraceWarning("Can't find the OpenIZ database, will re-install all migrations");
                            retVal.Configuration.GetSection <DataConfigurationSection>().MigrationLog.Entry.Clear();
                        }
                        retVal.SetProgress(context.GetString(Resource.String.startup_data), 0.6f);

                        DataMigrator migrator = new DataMigrator();
                        migrator.Ensure();

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

                        ApplicationServiceContext.Current  = ApplicationContext.Current;
                        ApplicationServiceContext.HostType = OpenIZHostType.MobileClient;
                    }
                    catch (Exception e)
                    {
                        retVal.m_tracer.TraceError(e.ToString());
                        throw;
                    }
                    finally
                    {
                        retVal.ConfigurationManager.Save();
                    }

                    // Is there a backup manager? If no then we will use the default backup manager


                    // Start daemons
                    ApplicationContext.Current.GetService <IUpdateManager>().AutoUpdate();
                    retVal.GetService <IThreadPoolService>().QueueNonPooledWorkItem(o => { retVal.Start(); }, null);

                    // Set the tracer writers for the PCL goodness!
                    foreach (var itm in retVal.Configuration.GetSection <DiagnosticsConfigurationSection>().TraceWriter)
                    {
                        OpenIZ.Core.Diagnostics.Tracer.AddWriter(itm.TraceWriter, itm.Filter);
                    }
                }
Пример #18
0
        /// <summary>
        /// Start the application context
        /// </summary>
        public static bool Start(DebuggerParameters consoleParms)
        {
            var retVal = new DebugApplicationContext();

            retVal.m_configurationManager = new DebugConfigurationManager(consoleParms);

            try
            {
                // Set master application context
                ApplicationContext.Current = retVal;

                retVal.ConfigurationManager.Load();
                retVal.m_tracer = Tracer.GetTracer(typeof(DebugApplicationContext), retVal.ConfigurationManager.Configuration);

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

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

                if (consoleParms.References != null)
                {
                    // Load references
                    foreach (var appletInfo in consoleParms.References)// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
                    {
                        try
                        {
                            retVal.m_tracer.TraceInfo("Loading applet {0}", appletInfo);
                            String appletPath = appletInfo;
                            if (!Path.IsPathRooted(appletInfo))
                            {
                                appletPath = Path.Combine(Environment.CurrentDirectory, appletPath);
                            }
                            using (var fs = File.OpenRead(appletPath))
                            {
                                var package = AppletPackage.Load(fs);
                                retVal.m_tracer.TraceInfo("Loading {0} v{1}", package.Meta.Id, package.Meta.Version);

                                // Is this applet in the allowed applets
                                appService.LoadApplet(package.Unpack());
                            }
                        }
                        catch (Exception e)
                        {
                            retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appletInfo, e.ToString());
                            throw;
                        }
                    }
                }

                // Ensure data migration exists
                try
                {
                    // If the DB File doesn't exist we have to clear the migrations
                    if (!File.Exists(retVal.Configuration.GetConnectionString(retVal.Configuration.GetSection <DataConfigurationSection>().MainDataSourceConnectionStringName).Value))
                    {
                        retVal.m_tracer.TraceWarning("Can't find the OpenIZ database, will re-install all migrations");
                        retVal.Configuration.GetSection <DataConfigurationSection>().MigrationLog.Entry.Clear();
                    }
                    retVal.SetProgress("Migrating databases", 0.6f);

                    DataMigrator migrator = new DataMigrator();
                    migrator.Ensure();

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

                    // Prepare clinical protocols
                    //retVal.GetService<ICarePlanService>().Repository = retVal.GetService<IClinicalProtocolRepositoryService>();
                    ApplicationServiceContext.Current  = ApplicationContext.Current;
                    ApplicationServiceContext.HostType = OpenIZHostType.OtherClient;
                }
                catch (Exception e)
                {
                    retVal.m_tracer.TraceError(e.ToString());
                    throw;
                }
                finally
                {
                    retVal.ConfigurationManager.Save();
                }

                // Set the tracer writers for the PCL goodness!
                foreach (var itm in retVal.Configuration.GetSection <DiagnosticsConfigurationSection>().TraceWriter)
                {
                    OpenIZ.Core.Diagnostics.Tracer.AddWriter(itm.TraceWriter, itm.Filter);
                }
                // Start daemons
                retVal.GetService <IThreadPoolService>().QueueUserWorkItem(o => { retVal.Start(); });

                //retVal.Start();
            }
            catch (Exception e)
            {
                retVal.m_tracer?.TraceError(e.ToString());
                throw;
            }
            return(true);
        }
Пример #19
0
        /// <summary>
        /// Starts the daemon service
        /// </summary>
        public bool Start()
        {
            this.m_tracer.TraceInfo("Starting applet manager service...");

            this.Starting?.Invoke(this, EventArgs.Empty);

            try
            {
                // Load packages from applets/ filesystem directory
                var appletDir = this.m_configuration.AppletDirectory;
                if (!Path.IsPathRooted(appletDir))
                {
                    appletDir = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), this.m_configuration.AppletDirectory);
                }

                if (!Directory.Exists(appletDir))
                {
                    this.m_tracer.TraceWarning("Applet directory {0} doesn't exist, no applets will be loaded", appletDir);
                }
                else
                {
                    this.m_tracer.TraceEvent(EventLevel.Verbose, "Scanning {0} for applets...", appletDir);
                    foreach (var f in Directory.GetFiles(appletDir).OrderBy(o => o.EndsWith(".sln.pak") ? 0 : 1))
                    {
                        // Try to open the file
                        this.m_tracer.TraceInfo("Loading {0}...", f);
                        using (var fs = File.OpenRead(f))
                        {
                            var pkg = AppletPackage.Load(fs);

                            if (pkg is AppletSolution) // We have loaded a solution
                            {
                                if (this.m_solutions.Any(o => o.Meta.Id == pkg.Meta.Id))
                                {
                                    this.m_tracer.TraceEvent(EventLevel.Critical, "Duplicate solution {0} is not permitted", pkg.Meta.Id);
                                    throw new DuplicateKeyException(pkg.Meta.Id);
                                }
                                else if (!this.Install(pkg as AppletSolution, true))
                                {
                                    throw new InvalidOperationException($"Could not install applet solution {pkg.Meta.Id}");
                                }
                            }
                            else if (this.m_fileDictionary.ContainsKey(pkg.Meta.Id))
                            {
                                this.m_tracer.TraceEvent(EventLevel.Warning, "Skipping duplicate package {0}", pkg.Meta.Id);
                                continue;
                            }
                            else if (this.Install(pkg, true))
                            {
                                //this.m_appletCollection.Add(pkg.Unpack());
                                //this.m_fileDictionary.Add(pkg.Meta.Id, f);
                            }
                            else
                            {
                                this.m_tracer.TraceEvent(EventLevel.Critical, "Cannot proceed while untrusted applets are present");
                                throw new SecurityException("Cannot proceed while untrusted applets are present");
                            }
                        }
                    }
                }
            }
            catch (SecurityException e)
            {
                this.m_tracer.TraceEvent(EventLevel.Error, "Error loading applets: {0}", e);
                throw new InvalidOperationException("Cannot proceed while untrusted applets are present");
            }
            catch (Exception ex)
            {
                this.m_tracer.TraceEvent(EventLevel.Error, "Error loading applets: {0}", ex);
                throw;
            }

            this.Started?.Invoke(this, EventArgs.Empty);
            return(true);
        }
Пример #20
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);
            }
        }
Пример #21
0
 /// <summary>
 /// Opens the specified package from the repository
 /// </summary>
 private AppletPackage OpenPackage(string filePath)
 {
     using (var s = System.IO.File.OpenRead(filePath))
         return(AppletPackage.Load(s));
 }
Пример #22
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
            {
                var retVal = new MiniApplicationContext();
                retVal.SetProgress("Run setup", 0);

                retVal.m_configurationManager = new MiniConfigurationManager(MiniConfigurationManager.GetDefaultConfiguration());

                ApplicationContext.Current         = retVal;
                ApplicationServiceContext.Current  = ApplicationContext.Current;
                ApplicationServiceContext.HostType = OpenIZHostType.OtherClient;

                retVal.m_tracer = Tracer.GetTracer(typeof(MiniApplicationContext));
                retVal.ThreadDefaultPrincipal = AuthenticationContext.SystemPrincipal;

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

                if (consoleParms.References != null)
                {
                    // Load references
                    foreach (var appletInfo in consoleParms.References)// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
                    {
                        try
                        {
                            retVal.m_tracer.TraceInfo("Loading applet {0}", appletInfo);
                            String appletPath = appletInfo;
                            if (!Path.IsPathRooted(appletInfo))
                            {
                                appletPath = Path.Combine(Environment.CurrentDirectory, appletPath);
                            }
                            using (var fs = File.OpenRead(appletPath))
                            {
                                var package = AppletPackage.Load(fs);
                                retVal.m_tracer.TraceInfo("Loading {0} v{1}", package.Meta.Id, package.Meta.Version);

                                // Is this applet in the allowed applets
                                appService.LoadApplet(package.Unpack());
                            }
                        }
                        catch (Exception e)
                        {
                            retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appletInfo, e.ToString());
                            throw;
                        }
                    }
                }

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

                // Load all user-downloaded applets in the data directory
                foreach (var appletDir in consoleParms.AppletDirectories)// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
                {
                    try
                    {
                        if (!Directory.Exists(appletDir) || !File.Exists(Path.Combine(appletDir, "manifest.xml")))
                        {
                            continue;
                        }

                        retVal.m_tracer.TraceInfo("Loading applet {0}", appletDir);
                        String appletPath = Path.Combine(appletDir, "manifest.xml");
                        using (var fs = File.OpenRead(appletPath))
                        {
                            AppletManifest manifest = AppletManifest.Load(fs);
                            (appService as MiniAppletManagerService).m_appletBaseDir.Add(manifest, appletDir);
                            // Is this applet in the allowed applets

                            // public key token match?
                            appService.LoadApplet(manifest);
                        }
                    }
                    catch (Exception e)
                    {
                        retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appletDir, e.ToString());
                        throw;
                    }
                }

                if (oizJs?.Content != null)
                {
                    oizJs.Content = oizJs.Content.ToString() + (appService as MiniAppletManagerService).GetShimMethods();
                }

                retVal.Start();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("OpenIZ FATAL: {0}", e.ToString());
                return(false);
            }
        }
Пример #23
0
        /// <summary>
        /// Start the application context
        /// </summary>
        public static bool Start(ConsoleParameters consoleParms)
        {
            var retVal = new MiniApplicationContext();

            retVal.m_configurationManager = new MiniConfigurationManager();
            // Not configured
            if (!retVal.ConfigurationManager.IsConfigured)
            {
                return(false);
            }
            else
            { // load configuration
                try
                {
                    // Set master application context
                    ApplicationContext.Current = retVal;

                    retVal.ConfigurationManager.Load();
                    retVal.AddServiceProvider(typeof(XamarinBackupService));

                    retVal.m_tracer = Tracer.GetTracer(typeof(MiniApplicationContext), retVal.ConfigurationManager.Configuration);

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

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

                    if (consoleParms.References != null)
                    {
                        // Load references
                        foreach (var appletInfo in consoleParms.References)// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
                        {
                            try
                            {
                                retVal.m_tracer.TraceInfo("Loading applet {0}", appletInfo);
                                String appletPath = appletInfo;
                                if (!Path.IsPathRooted(appletInfo))
                                {
                                    appletPath = Path.Combine(Environment.CurrentDirectory, appletPath);
                                }
                                using (var fs = File.OpenRead(appletPath))
                                {
                                    var package = AppletPackage.Load(fs);
                                    retVal.m_tracer.TraceInfo("Loading {0} v{1}", package.Meta.Id, package.Meta.Version);

                                    // Is this applet in the allowed applets
                                    appService.LoadApplet(package.Unpack());
                                }
                            }
                            catch (Exception e)
                            {
                                retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appletInfo, e.ToString());
                                throw;
                            }
                        }
                    }

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

                    // Load all user-downloaded applets in the data directory
                    foreach (var appletDir in consoleParms.AppletDirectories)// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
                    {
                        try
                        {
                            if (!Directory.Exists(appletDir) || !File.Exists(Path.Combine(appletDir, "manifest.xml")))
                            {
                                continue;
                            }

                            retVal.m_tracer.TraceInfo("Loading applet {0}", appletDir);
                            String appletPath = Path.Combine(appletDir, "manifest.xml");
                            using (var fs = File.OpenRead(appletPath))
                            {
                                AppletManifest manifest = AppletManifest.Load(fs);
                                (appService as MiniAppletManagerService).m_appletBaseDir.Add(manifest, appletDir);
                                // Is this applet in the allowed applets

                                // public key token match?
                                appService.LoadApplet(manifest);
                            }
                        }
                        catch (Exception e)
                        {
                            retVal.m_tracer.TraceError("Loading applet {0} failed: {1}", appletDir, e.ToString());
                            throw;
                        }
                    }

                    if (oizJs?.Content != null)
                    {
                        oizJs.Content = oizJs.Content.ToString() + (appService as MiniAppletManagerService).GetShimMethods();
                    }

                    // Ensure data migration exists
                    try
                    {
                        // If the DB File doesn't exist we have to clear the migrations
                        if (!File.Exists(retVal.Configuration.GetConnectionString(retVal.Configuration.GetSection <DataConfigurationSection>().MainDataSourceConnectionStringName).Value))
                        {
                            retVal.m_tracer.TraceWarning("Can't find the OpenIZ database, will re-install all migrations");
                            retVal.Configuration.GetSection <DataConfigurationSection>().MigrationLog.Entry.Clear();
                        }
                        retVal.SetProgress("Migrating databases", 0.6f);

                        DataMigrator migrator = new DataMigrator();
                        migrator.Ensure();

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

                        // Prepare clinical protocols
                        //retVal.GetService<ICarePlanService>().Repository = retVal.GetService<IClinicalProtocolRepositoryService>();
                        ApplicationServiceContext.Current  = ApplicationContext.Current;
                        ApplicationServiceContext.HostType = OpenIZHostType.OtherClient;
                    }
                    catch (Exception e)
                    {
                        retVal.m_tracer.TraceError(e.ToString());
                        throw;
                    }
                    finally
                    {
                        retVal.ConfigurationManager.Save();
                    }

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


                    // Set the tracer writers for the PCL goodness!
                    foreach (var itm in retVal.Configuration.GetSection <DiagnosticsConfigurationSection>().TraceWriter)
                    {
                        OpenIZ.Core.Diagnostics.Tracer.AddWriter(itm.TraceWriter, itm.Filter);
                    }
                    // Start daemons
                    retVal.GetService <IThreadPoolService>().QueueUserWorkItem(o => { retVal.Start(); });

                    //retVal.Start();
                }
                catch (Exception e)
                {
                    retVal.m_tracer?.TraceError(e.ToString());
                    //ApplicationContext.Current = null;
                    retVal.m_configurationManager = new MiniConfigurationManager(MiniConfigurationManager.GetDefaultConfiguration());
                    throw;
                }
                return(true);
            }
        }
Пример #24
0
        /// <summary>
        /// Load external references
        /// </summary>
        private static void LoadReferences(MiniApplicationContext context, StringCollection references)
        {
            var appService = context.GetService <IAppletManagerService>();

            // Load references
            foreach (var appletInfo in references)// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
            {
                try
                {
                    context.m_tracer.TraceInfo("Loading applet {0}", appletInfo);

                    String appletPath = appletInfo;

                    // Is there a pak extension?
                    if (Path.GetExtension(appletPath) != ".pak")
                    {
                        appletPath += ".pak";
                    }

                    if (!Path.IsPathRooted(appletInfo))
                    {
                        appletPath = Path.Combine(Environment.CurrentDirectory, appletPath);
                    }

                    // Does the reference exist in the current directory?
                    if (!File.Exists(appletPath))
                    {
                        appletPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), Path.GetFileName(appletPath));
                    }

                    AppletPackage package = null;
                    if (!File.Exists(appletPath)) // Fetch from Repo
                    {
                        Console.WriteLine("Attempting to locate {0}", appletInfo);
                        var data = appletInfo.Split(';');
                        if (data.Length == 1)
                        {
                            package = PakMan.Repository.PackageRepositoryUtil.GetFromAny(appletInfo, null);
                        }
                        else
                        {
                            package = PakMan.Repository.PackageRepositoryUtil.GetFromAny(data[0], new Version(data[1]));
                        }
                    }
                    else
                    {
                        Console.WriteLine("Including {0}...", appletPath);
                        using (var fs = File.OpenRead(appletPath))
                        {
                            package = AppletPackage.Load(fs);
                        }
                    }

                    if (package == null)
                    {
                        throw new InvalidOperationException($"Cannot find reference {appletInfo}");
                    }

                    if (package is AppletSolution)
                    {
                        // Look for other applets with this
                        foreach (var itm in (package as AppletSolution).Include)
                        {
                            context.m_tracer.TraceInfo("Loading solution content project {0}", itm.Meta.Id);
                            appService.LoadApplet(itm.Unpack());
                        }
                    }
                    else
                    {
                        context.m_tracer.TraceInfo("Loading {0} v{1}", package.Meta.Id, package.Meta.Version);
                        // Is this applet in the allowed applets
                        appService.LoadApplet(package.Unpack());
                    }
                }
                catch (Exception e)
                {
                    context.m_tracer.TraceError("Loading applet {0} failed: {1}", appletInfo, e.ToString());
                    throw;
                }
            }
        }