/// <summary>
        /// Load applets in <paramref name="appletDirectories"/>
        /// </summary>
        private static void LoadApplets(IEnumerable <String> appletDirectories, IAppletManagerService appService)
        {
            foreach (var appletDir in appletDirectories)// Directory.GetFiles(this.m_configuration.GetSection<AppletConfigurationSection>().AppletDirectory)) {
            {
                try
                {
                    if (!Directory.Exists(appletDir) || !File.Exists(Path.Combine(appletDir, "manifest.xml")))
                    {
                        throw new DirectoryNotFoundException($"Applet {appletDir} not found");
                    }

                    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)
                {
                    throw;
                }
            }
        }
 public void Initialize()
 {
     this.m_appletCollection.Add(AppletManifest.Load(typeof(TestRenderApplets).Assembly.GetManifestResourceStream("SanteDB.Core.Applets.Test.HelloWorldApplet.xml")));
     this.m_appletCollection.Add(AppletManifest.Load(typeof(TestRenderApplets).Assembly.GetManifestResourceStream("SanteDB.Core.Applets.Test.SettingsApplet.xml")));
     this.m_appletCollection.Add(AppletManifest.Load(typeof(TestRenderApplets).Assembly.GetManifestResourceStream("SanteDB.Core.Applets.Test.LocalizationWithJavascript.xml")));
     this.m_appletCollection.Add(AppletManifest.Load(typeof(TestRenderApplets).Assembly.GetManifestResourceStream("SanteDB.Core.Applets.Test.LayoutAngularTest.xml")));
 }
Exemple #3
0
        /// <summary>
        /// File system watcher has changed, re-process directory
        /// </summary>
        private void fsw_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                // Get the applet that this change is for
                var fsWatcherInfo = this.m_fsWatchers.First(o => o.Value == sender);
                var applet        = this.m_appletCollection.First(o => o.Info.Id == fsWatcherInfo.Key);
                var asset         = applet.Assets.FirstOrDefault(o => o.Name.Equals(e.FullPath.Replace(fsWatcherInfo.Value.Path, "").Replace("\\", "/"), StringComparison.OrdinalIgnoreCase));

                switch (e.ChangeType)
                {
                case WatcherChangeTypes.Created:     // file has been created
                case WatcherChangeTypes.Changed:

                    if (!File.Exists(e.FullPath))
                    {
                        return;
                    }
                    // Wait until file is not locked so we can process it
                    bool isEmpty = false;
                    while (this.IsFileLocked(e.FullPath, out isEmpty))
                    {
                        Thread.Sleep(100);
                    }
                    if (isEmpty)
                    {
                        return;
                    }

                    // Manifest has changed so re-process
                    if (e.Name.ToLower() == "manifest.xml")
                    {
                        if (!IsFileLocked(e.FullPath, out isEmpty) && !isEmpty)
                        {
                            try
                            {
                                using (var fs = File.OpenRead(e.FullPath))
                                {
                                    var newManifest = AppletManifest.Load(fs);
                                    applet.Configuration = newManifest.Configuration;
                                    applet.Info          = newManifest.Info;
                                    applet.Menus         = newManifest.Menus;
                                    applet.StartAsset    = newManifest.StartAsset;
                                    applet.Strings       = newManifest.Strings;
                                    applet.Templates     = newManifest.Templates;
                                    applet.ViewModel     = newManifest.ViewModel;
                                }
                            }
                            catch (IOException)
                            {
                                throw;
                            }
                        }
                        catch (Exception ex)
                        {
                            this.m_tracer.TraceError("Error re-reading manifest: {0}", ex);
                        }
                    }
        public void TestLayoutBundleReferences()
        {
            var coll = new AppletCollection();

            coll.Add(AppletManifest.Load(typeof(TestRenderApplets).Assembly.GetManifestResourceStream("SanteDB.Core.Applets.Test.LayoutAngularTest.xml")));

            var    asset  = coll.ResolveAsset("app://org.santedb.applet.test.layout/index.html");
            var    render = coll.RenderAssetContent(asset);
            string html   = Encoding.UTF8.GetString(render);

            Assert.IsTrue(html.Contains("index-controller"), "Missing index-controller");
            Assert.IsTrue(html.Contains("layout-controller"), "Missing layout-controller");
            Assert.IsTrue(html.Contains("index-style"), "Missing index-style");
            Assert.IsTrue(html.Contains("layout-controller"), "Missing layout-style");
        }
        /// <summary>
        /// Load a solution file and all referneced applets
        /// </summary>
        private static void LoadSolution(String solutionFile, IAppletManagerService appService)
        {
            using (var fs = File.OpenRead(solutionFile))
            {
                var solution = AppletManifest.Load(fs);

                // Load include elements
                var solnDir = Path.GetDirectoryName(solutionFile);

                // Preload any manifests
                var refManifests = new Dictionary <String, AppletManifest>();
                // Load reference manifests
                foreach (var mfstFile in Directory.GetFiles(solnDir, "manifest.xml", SearchOption.AllDirectories))
                {
                    using (var manifestStream = File.OpenRead(mfstFile))
                    {
                        refManifests.Add(Path.GetDirectoryName(mfstFile), AppletManifest.Load(manifestStream));
                    }
                }

                // Load dependencies
                foreach (var dep in solution.Info.Dependencies)
                {
                    // Attempt to load the appropriate manifest file
                    var cand = refManifests.FirstOrDefault(o => o.Value.Info.Id == dep.Id);
                    if (cand.Value != null)
                    {
                        (appService as MiniAppletManagerService).m_appletBaseDir.Add(cand.Value, cand.Key);
                        // Is this applet in the allowed applets

                        // public key token match?
                        appService.LoadApplet(cand.Value);
                    }
                }
            }
        }
Exemple #6
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);
            }
        }
Exemple #7
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);
            }
        }
        /// <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);
                    }
                }
Exemple #9
0
        /// <summary>
        /// Compose multiple PAK files into a solution
        /// </summary>
        public int Compose()
        {
            try
            {
                AppletManifest mfst = null;
                using (FileStream fs = File.OpenRead(this.m_parms.Source))
                    mfst = AppletManifest.Load(fs);

                var slnPak = mfst.CreatePackage();

                AppletSolution sln = new AppletSolution();
                sln.Meta      = slnPak.Meta;
                sln.PublicKey = slnPak.PublicKey;
                sln.Manifest  = slnPak.Manifest;

                if (sln.Meta.Uuid == Guid.Empty)
                {
                    Emit.Message("WARN", "The package does not carry a UUID! You should add a UUID to your solution manifest");
                }
                sln.Include = new List <AppletPackage>();

                foreach (var pfile in sln.Meta.Dependencies.ToArray())
                {
                    AppletPackage pkg = null;
                    if (!String.IsNullOrEmpty(pfile.Version)) // specific version
                    {
                        pkg = PackageRepositoryUtil.GetFromAny(pfile.Id, new Version(pfile.Version));
                    }
                    else if (!String.IsNullOrEmpty(m_parms.Version))
                    {
                        pkg = PackageRepositoryUtil.GetFromAny(pfile.Id, new Version(m_parms.Version))
                              ?? PackageRepositoryUtil.GetFromAny(pfile.Id, null);
                    }
                    else
                    {
                        pkg = PackageRepositoryUtil.GetFromAny(pfile.Id, null);
                    }

                    if (pkg == null)
                    {
                        throw new KeyNotFoundException($"Package {pfile.Id} ({pfile.Version ?? m_parms.Version ?? "latest"}) not found");
                    }
                    else
                    {
                        Emit.Message("INFO", "Including {0} version {1}..", pkg.Meta.Id, pkg.Meta.Version);
                        sln.Meta.Dependencies.RemoveAll(o => o.Id == pkg.Meta.Id);

                        if (this.m_parms.Sign && pkg.Meta.Signature == null)
                        {
                            Emit.Message("WARN", "Package {0} is not signed, but you're signing your package. We'll sign it using your key", pkg.Meta.Id);
                            pkg = new Signer(this.m_parms).CreateSignedPackage(pkg.Unpack());
                        }
                        sln.Include.Add(pkg);
                    }
                }

                // Emit i18n file?
                if (!String.IsNullOrEmpty(this.m_parms.InternationalizationFile))
                {
                    Emit.Message("INFO", $"Writing string manifest to {this.m_parms.InternationalizationFile}");
                    using (var fs = File.Create(this.m_parms.InternationalizationFile))
                        using (var tw = new StreamWriter(fs, System.Text.Encoding.UTF8))
                        {
                            // tx translations
                            var mfsts         = sln.Include.Select(o => o.Unpack()).ToList();
                            var appletStrings = mfsts.SelectMany(o => o.Strings).ToArray();
                            var stringKeys    = appletStrings.SelectMany(o => o.String).Select(o => o.Key).Distinct();
                            var langs         = appletStrings.Select(o => o.Language).Distinct().ToArray();
                            tw.Write("key,");
                            tw.WriteLine(String.Join(",", langs));

                            foreach (var str in stringKeys)
                            {
                                tw.Write($"{str},");
                                foreach (var lang in langs)
                                {
                                    tw.Write($"\"{appletStrings.Where(o => o.Language == lang).SelectMany(s => s.String).FirstOrDefault(o => o.Key == str)?.Value}\",");
                                }
                                tw.WriteLine();
                            }
                        }
                }

                sln.Meta.Hash = SHA256.Create().ComputeHash(sln.Include.SelectMany(o => o.Manifest).ToArray());
                // Sign the signature package
                if (this.m_parms.Sign)
                {
                    new Signer(this.m_parms).CreateSignedSolution(sln);
                }

                // Now save
                using (FileStream fs = File.Create(this.m_parms.Output ?? Path.ChangeExtension(sln.Meta.Id, ".sln.pak")))
                    sln.Save(fs);

                return(0);
            }
            catch (System.Exception e)
            {
                Emit.Message("ERROR", e.Message);
                //Console.Error.WriteLine("Cannot compose solution {0}: {1}", this.m_parms.Source, e);
                return(-1);
            }
        }
        /// <summary>
        /// Start the application context
        /// </summary>
        public static bool StartContext(IDialogProvider dialogProvider)
        {
            var retVal = new DcApplicationContext(dialogProvider);

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

                    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(XamarinBackupService));

                    // 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
                    retVal.Configuration.GetSection <ApplicationConfigurationSection>().AppSettings.Add(new AppSettingKeyValuePair()
                    {
                        Key   = "ignore.restore",
                        Value = "true"
                    });

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

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

                    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);
                            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 (AppDomainUnloadedException) { throw; }
                    }
                    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);
                            }
                        }
                        else
                        {
                            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();
                }
Exemple #11
0
        /// <summary>
        /// Compile
        /// </summary>
        public int Compile()
        {
            int retVal = 0;

            // First is there a Manifest.xml?
            if (!Path.IsPathRooted(this.m_parms.Source))
            {
                this.m_parms.Source = Path.Combine(Environment.CurrentDirectory, this.m_parms.Source);
            }


            Console.WriteLine("Processing {0}...", this.m_parms.Source);

            String manifestFile = this.m_parms.Source;

            if (!File.Exists(manifestFile) && Directory.Exists(manifestFile))
            {
                manifestFile = Path.Combine(this.m_parms.Source, "manifest.xml");
            }

            if (!File.Exists(manifestFile))
            {
                throw new InvalidOperationException($"Directory {this.m_parms.Source} must have manifest.xml");
            }
            else
            {
                Console.WriteLine("\t Reading Manifest...", manifestFile);

                using (var fs = File.OpenRead(manifestFile))
                {
                    AppletManifest mfst = AppletManifest.Load(fs);
                    mfst.Assets.AddRange(this.ProcessDirectory(Path.GetDirectoryName(manifestFile), Path.GetDirectoryName(manifestFile)));
                    foreach (var i in mfst.Assets)
                    {
                        if (i.Name.StartsWith("/"))
                        {
                            i.Name = i.Name.Substring(1);
                        }
                    }

                    if (!string.IsNullOrEmpty(this.m_parms.Version))
                    {
                        mfst.Info.Version = this.m_parms.Version;
                    }
                    mfst.Info.Version = PakManTool.ApplyVersion(mfst.Info.Version);

                    if (!Directory.Exists(Path.GetDirectoryName(this.m_parms.Output)) && !String.IsNullOrEmpty(Path.GetDirectoryName(this.m_parms.Output)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(this.m_parms.Output));
                    }

                    AppletPackage pkg = null;

                    // Is there a signature?
                    if (this.m_parms.Sign)
                    {
                        pkg = new Signer(this.m_parms).CreateSignedPackage(mfst);
                        if (pkg == null)
                        {
                            return(-102);
                        }
                    }
                    else
                    {
                        Emit.Message("WARN", "THIS PACKAGE IS NOT SIGNED - MOST OPEN IZ TOOLS WILL NOT LOAD IT");
                        mfst.Info.PublicKeyToken = null;
                        pkg = mfst.CreatePackage();
                        //pkg.Meta.PublicKeyToken = null;
                    }
                    pkg.Meta.Hash = SHA256.Create().ComputeHash(pkg.Manifest);

                    var outFile = this.m_parms.Output ?? mfst.Info.Id + ".pak";
                    using (var ofs = File.Create(outFile))
                        pkg.Save(ofs);

                    if (this.m_parms.Install)
                    {
                        Emit.Message("INFO", "INSTALLING PACKAGE {0}", pkg.Meta.Id);
                        PackageRepositoryUtil.InstallCache(pkg);
                    }
                    if (this.m_parms.Publish)
                    {
                        try
                        {
                            Emit.Message("INFO", "PUBLISHING PACKAGE TO {0}", this.m_parms.PublishServer);
                            PackageRepositoryUtil.Publish(this.m_parms.PublishServer, pkg);
                        }
                        catch (Exception e)
                        {
                            Emit.Message("ERROR", "ERROR PUBLISHING PACKAGE - {0}", e.Message);
                        }
                    }
                }
            }

            return(retVal);
        }
Exemple #12
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);
            }
        }