Ejemplo n.º 1
0
        /// <summary>
        /// Serialize the applet to a file
        /// </summary>
        private void SerializeApplet(AppletPackage pkg, string target, String csproj = null)
        {
            Emit.Message("INFO", "Slipsteam {0} -> {1}", pkg.Meta.Id, target);

            // Add the file
            using (var fs = File.Create(Path.Combine(target, pkg.Meta.Id) + ".pak"))
                pkg.Save(fs);

            // Save the CSPROJ info
            if (!String.IsNullOrEmpty(csproj))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(csproj);
                // Get Android Assets - Do they exist for this object?
                var assetPath = Path.Combine(target.Replace(Path.GetDirectoryName(csproj), "").Substring(1), pkg.Meta.Id + ".pak");

                var node = doc.SelectSingleNode($"//*[local-name() = 'AndroidAsset'][@Include = '{assetPath}']");
                if (node == null)
                {
                    var itemElement = doc.CreateElement("ItemGroup", "http://schemas.microsoft.com/developer/msbuild/2003")
                                      .AppendChild(doc.CreateElement("AndroidAsset", "http://schemas.microsoft.com/developer/msbuild/2003"))
                                      .Attributes.Append(doc.CreateAttribute("Include"));
                    itemElement.Value = assetPath;
                    doc.DocumentElement.AppendChild(itemElement.OwnerElement.ParentNode);
                    doc.Save(csproj);
                }
            }
        }
Ejemplo n.º 2
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);
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Publish to the specified service
 /// </summary>
 public static AppletInfo Publish(String serverUrl, AppletPackage package)
 {
     try
     {
         if (String.IsNullOrEmpty(serverUrl))
         {
             foreach (var c in s_configuration.Repository)
             {
                 c.GetRepository().Put(package);
             }
             return(package.Meta);
         }
         else
         {
             var config = s_configuration.Repository.Find(o => o.Path == serverUrl);
             if (config == null)
             {
                 throw new KeyNotFoundException($"Configuration for {serverUrl} not found");
             }
             return(config.GetRepository().Put(package));
         }
     }
     catch (RestClientException e)
     {
         throw new Exception($"PUT Failed - {e.Status} - {e.Message} - {e.Result?.Message}");
     }
     catch (Exception e)
     {
         throw new Exception($"PUT Failed - {e.Message}", e);
     }
 }
        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)));
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Updates an applet.
 /// </summary>
 /// <param name="appletId">The id of the applet to be updated.</param>
 /// <param name="appletPackage">The applet containing the updated information.</param>
 /// <returns>Returns the updated applet.</returns>
 public AppletManifestInfo UpdateApplet(Guid appletId, AppletPackage appletPackage)
 {
     using (var ms = new MemoryStream())
     {
         appletPackage.Save(ms);
         ms.Flush();
         return(this.Client.Put <byte[], AppletManifestInfo>($"Applet/{appletId}", "application/octet-stream", ms.ToArray()));
     }
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Creates an applet.
 /// </summary>
 /// <returns>Returns the created applet manifest info.</returns>
 public AppletManifestInfo CreateApplet(AppletPackage appletPackage)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         appletPackage.Save(ms);
         ms.Flush();
         return(this.Client.Post <byte[], AppletManifestInfo>("Applet", "application/octet-stream", ms.ToArray()));
     }
 }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Starts the application context using in-memory default configuration for the purposes of
        /// configuring the software
        /// </summary>
        /// <returns><c>true</c>, if temporary was started, <c>false</c> otherwise.</returns>
        public static bool StartTemporary(IDialogProvider dialogProvider, String instanceName, SecurityApplication applicationId, SanteDBHostType hostType)
        {
            try
            {
                var retVal = new DcApplicationContext(dialogProvider, instanceName, applicationId, hostType);
                retVal.SetProgress("Run setup", 0);
                //retVal.AddServiceProvider(typeof(ConfigurationManager));
                ApplicationServiceContext.Current = DcApplicationContext.Current = retVal;
                retVal.m_tracer = Tracer.GetTracer(typeof(DcApplicationContext));
                var configuration = retVal.Configuration.GetSection <DiagnosticsConfigurationSection>();
                foreach (var tr in configuration.TraceWriter)
                {
                    Tracer.AddWriter(Activator.CreateInstance(tr.TraceWriter, tr.Filter, tr.InitializationData, configuration.Sources.ToDictionary(o => o.SourceName, o => o.Filter)) as TraceWriter, tr.Filter);
                }
                retVal.GetService <IServiceManager>().AddServiceProvider(typeof(DefaultBackupService));

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

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

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

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("SanteDB FATAL: {0}", e.ToString());
                return(false);
            }
        }
Ejemplo n.º 10
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);
            }
        }
Ejemplo n.º 11
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));
            }
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Install the package
 /// </summary>
 public AppletInfo Put(AppletPackage package)
 {
     // Locate the specified package
     try
     {
         using (var ms = new MemoryStream())
         {
             package.Save(ms);
             return(this.m_client.Put <MemoryStream, AppletInfo>("pak", new MemoryStream(ms.ToArray())));
         }
     }
     catch (RestClientException e)
     {
         this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, "Error pushing package {0}: {1}", package.Meta, e);
         throw;
     }
 }
Ejemplo n.º 13
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
            {
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Package the assets
        /// </summary>
        /// <returns></returns>
        public int Package()
        {
            using (FileStream fs = File.OpenRead(this.m_parameters.Output))
                this.m_package = AppletSolution.Load(fs);

            // Package the android APK project
            if (this.m_parameters.DcdrAssets.Contains("android"))
            {
                this.PackageApk();
            }

            // Package the DCG project
            if (this.m_parameters.DcdrAssets.Contains("gateway"))
            {
                this.PackageDcg();
            }

            return(1);
        }
Ejemplo n.º 15
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)));
        }
        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));
            }
        }
Ejemplo n.º 17
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);
            }
        }
Ejemplo n.º 18
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;
            }
        }
Ejemplo n.º 19
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);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Get specified package from any package repository
        /// </summary>
        public static AppletPackage GetFromAny(String packageId, Version packageVersion)
        {
            AppletPackage retVal = null;

            try
            {
                return(s_localCache.GetRepository().Get(packageId, packageVersion, true));
            }
            catch
            {
                foreach (var rep in s_configuration.Repository)
                {
                    try
                    {
                        retVal = rep.GetRepository().Get(packageId, packageVersion);
                        if (retVal == null)
                        {
                            continue;
                        }

                        if (packageVersion == null || retVal.Version == packageVersion.ToString())
                        {
                            if (!LocalCachePath.Equals(rep.Path))
                            {
                                PackageRepositoryUtil.InstallCache(retVal);
                            }
                            break;
                        }
                    }
                    catch
                    {
                    }
                }
            }


            return(retVal);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Installs a package into the package repository
        /// </summary>
        public AppletInfo Put(AppletPackage package)
        {
            if (this.m_packageInfos == null)
            {
                throw new InvalidOperationException("Package repository is not initialized");
            }
            else if (String.IsNullOrEmpty(package.Meta?.Id))
            {
                throw new ArgumentNullException("Package must have ID");
            }
            else if (String.IsNullOrEmpty(package.Meta?.Version))
            {
                throw new ArgumentNullException("Package must have version");
            }

            try
            {
                var targetPath = Path.Combine(this.GetRepositoryPath(), $"{package.Meta.Id}-{package.Meta.Version}.pak");
                if (!Directory.Exists(Path.GetDirectoryName(targetPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
                }
                using (var fs = System.IO.File.Create(targetPath))
                    package.Save(fs);

                // Add the file to the repository
                lock (this.m_lockObject)
                    if (!this.m_packageInfos.ContainsKey(targetPath))
                    {
                        this.m_packageInfos.Add(targetPath, package.Meta);
                    }
                return(package.Meta);
            }
            catch (System.Exception e)
            {
                throw new System.Exception($"Could not install package {package.Meta.Id} v {package.Meta.Version}", e);
            }
        }
Ejemplo n.º 22
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)));
        }
        /// <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));
            }
        }
Ejemplo n.º 24
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)));
        }
Ejemplo n.º 25
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);
            }
        }
Ejemplo n.º 26
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);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Performs an installation
        /// </summary>
        public virtual bool Install(AppletPackage package, bool isUpgrade = false)
        {
            this.m_tracer.TraceWarning("Installing {0}", package.Meta);

            // TODO: Verify package hash / signature
            if (!this.VerifyPackage(package))
            {
                throw new SecurityException("Applet failed validation");
            }
            else if (!this.m_appletCollection.VerifyDependencies(package.Meta))
            {
                this.m_tracer.TraceWarning($"Applet {package.Meta} depends on : [{String.Join(", ", package.Meta.Dependencies.Select(o => o.ToString()))}] which are missing or incompatible");
            }
            var    appletSection = ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>();
            String appletPath    = Path.Combine(appletSection.AppletDirectory, package.Meta.Id);

            try
            {
                // Desearialize an prep for install

                this.m_tracer.TraceInfo("Installing applet {0} (IsUpgrade={1})", package.Meta, isUpgrade);

                ApplicationContext.Current.SetProgress(package.Meta.GetName("en"), 0.0f);
                // TODO: Verify the package

                // Copy
                if (!Directory.Exists(appletSection.AppletDirectory))
                {
                    Directory.CreateDirectory(appletSection.AppletDirectory);
                }

                if (File.Exists(appletPath))
                {
                    if (!isUpgrade)
                    {
                        throw new InvalidOperationException(Strings.err_duplicate_package_name);
                    }

                    // Unload the loaded applet version
                    var existingApplet = this.m_appletCollection.FirstOrDefault(o => o.Info.Id == package.Meta.Id);
                    if (existingApplet != null)
                    {
                        this.UnInstallInternal(existingApplet);
                    }
                }

                var mfst = package.Unpack();
                // Migrate data.
                if (mfst.DataSetup != null)
                {
                    foreach (var itm in mfst.DataSetup.Action)
                    {
                        Type idpType = typeof(IDataPersistenceService <>);
                        idpType = idpType.MakeGenericType(new Type[] { itm.Element.GetType() });
                        var svc = ApplicationContext.Current.GetService(idpType);
                        idpType.GetMethod(itm.ActionName).Invoke(svc, new object[] { itm.Element, TransactionMode.Commit, AuthenticationContext.SystemPrincipal });
                    }
                }

                // Now export all the binary files out
                var assetDirectory = Path.Combine(appletSection.AppletDirectory, "assets", mfst.Info.Id);
                if (!Directory.Exists(assetDirectory))
                {
                    Directory.CreateDirectory(assetDirectory);
                }
                else
                {
                    Directory.Delete(assetDirectory, true);
                }

                for (int i = 0; i < mfst.Assets.Count; i++)
                {
                    var itm     = mfst.Assets[i];
                    var itmPath = Path.Combine(assetDirectory, itm.Name);
                    ApplicationContext.Current.SetProgress($"Installing {package.Meta.GetName("en")}", 0.1f + (float)(0.8 * (float)i / mfst.Assets.Count));

                    // Get dir name and create
                    if (!Directory.Exists(Path.GetDirectoryName(itmPath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(itmPath));
                    }

                    // Extract content
                    if (itm.Content is byte[])
                    {
                        if (Encoding.UTF8.GetString(itm.Content as byte[], 0, 4) == "LZIP")
                        {
                            using (var fs = File.Create(itmPath))
                                using (var ms = new MemoryStream(itm.Content as byte[]))
                                    using (var lzs = new LZipStream(new NonDisposingStream(ms), SharpCompress.Compressors.CompressionMode.Decompress))
                                        lzs.CopyTo(fs);
                        }
                        else
                        {
                            File.WriteAllBytes(itmPath, itm.Content as byte[]);
                        }
                        itm.Content = null;
                    }
                    else if (itm.Content is String)
                    {
                        File.WriteAllText(itmPath, itm.Content as String);
                        itm.Content = null;
                    }
                }

                // Serialize the data to disk
                using (FileStream fs = File.Create(appletPath))
                    mfst.Save(fs);

                // For now sign with SHA256
                SHA256 sha = SHA256.Create();
                package.Meta.Hash = sha.ComputeHash(File.ReadAllBytes(appletPath));
                // HACK: Re-re-remove
                appletSection.Applets.RemoveAll(o => o.Id == package.Meta.Id);
                appletSection.Applets.Add(package.Meta.AsReference());

                ApplicationContext.Current.SetProgress(package.Meta.GetName("en"), 0.98f);

                if (ApplicationContext.Current.ConfigurationPersister.IsConfigured)
                {
                    ApplicationContext.Current.ConfigurationPersister.Save(ApplicationContext.Current.Configuration);
                }

                this.LoadApplet(mfst);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error installing applet {0} : {1}", package.Meta.ToString(), e);

                // Remove
                if (File.Exists(appletPath))
                {
                    File.Delete(appletPath);
                }

                throw;
            }

            return(true);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Compile
        /// </summary>
        static int Compile(ConsoleParameters parameters)
        {
            int retVal = 0;

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

            // Applet collection
            AppletCollection ac  = new AppletCollection();
            XmlSerializer    xsz = new XmlSerializer(typeof(AppletManifest));
            XmlSerializer    xpz = new XmlSerializer(typeof(AppletPackage));

            if (parameters.References != null)
            {
                foreach (var itm in parameters.References)
                {
                    if (File.Exists(itm))
                    {
                        using (var fs = File.OpenRead(itm))
                        {
                            if (Path.GetExtension(itm) == ".pak")
                            {
                                using (var gzs = new GZipStream(fs, CompressionMode.Decompress))
                                {
                                    var pack = xpz.Deserialize(gzs) as AppletPackage;
                                    var mfst = pack.Unpack();
                                    mfst.Initialize();
                                    ac.Add(mfst);
                                    Console.WriteLine("Added reference to {0}; v={1}", mfst.Info.Id, mfst.Info.Version);
                                }
                            }
                            else
                            {
                                var mfst = xsz.Deserialize(fs) as AppletManifest;
                                mfst.Initialize();
                                ac.Add(mfst);
                                Console.WriteLine("Added reference to {0}; v={1}", mfst.Info.Id, mfst.Info.Version);
                            }
                        }
                    }
                }
            }

            Console.WriteLine("Processing {0}...", parameters.Source);
            String manifestFile = Path.Combine(parameters.Source, "manifest.xml");

            if (!File.Exists(manifestFile))
            {
                Console.WriteLine("Directory must have manifest.xml");
            }
            else
            {
                Console.WriteLine("\t Reading Manifest...", parameters.Source);

                using (var fs = File.OpenRead(manifestFile))
                {
                    AppletManifest mfst = xsz.Deserialize(fs) as AppletManifest;
                    mfst.Assets.AddRange(ProcessDirectory(parameters.Source, parameters.Source, parameters));
                    foreach (var i in mfst.Assets)
                    {
                        i.Name = i.Name.Substring(1);
                    }

                    if (mfst.Info.Version.Contains("*"))
                    {
                        mfst.Info.Version = mfst.Info.Version.Replace("*", (((DateTime.Now.Subtract(new DateTime(DateTime.Now.Year, 1, 1)).Ticks >> 24) % 10000)).ToString("0000"));
                    }

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

                    AppletPackage pkg = null;

                    // Is there a signature?
                    if (!String.IsNullOrEmpty(parameters.SignKey))
                    {
                        pkg = CreateSignedPackage(mfst, parameters);
                        if (pkg == null)
                        {
                            return(-102);
                        }
                    }
                    else
                    {
                        Console.WriteLine("WARNING:>>> THIS PACKAGE IS NOT SIGNED - MOST OPEN IZ TOOLS WILL NOT LOAD IT");
                        mfst.Info.PublicKeyToken = null;
                        pkg = mfst.CreatePackage(parameters.Compression);
                        //pkg.Meta.PublicKeyToken = null;
                    }
                    pkg.Meta.Hash = SHA256.Create().ComputeHash(pkg.Manifest);

                    using (var ofs = File.Create(Path.ChangeExtension(parameters.Output ?? "out.pak", ".pak")))
                    {
                        pkg.Save(ofs);
                    }
                    // Render the build directory

                    if (!String.IsNullOrEmpty(parameters.Deploy))
                    {
                        var bindir = Path.Combine(Path.GetDirectoryName(parameters.Output), "bin");

                        if (String.IsNullOrEmpty(parameters.Deploy))
                        {
                            if (Directory.Exists(bindir) && parameters.Clean)
                            {
                                Directory.Delete(bindir, true);
                            }
                            bindir = Path.Combine(bindir, mfst.Info.Id);
                            Directory.CreateDirectory(bindir);
                        }
                        else
                        {
                            bindir = parameters.Deploy;
                        }

                        mfst.Initialize();
                        ac.Add(mfst);

                        foreach (var lang in mfst.Strings)
                        {
                            string wd = Path.Combine(bindir, lang.Language);
                            if (String.IsNullOrEmpty(parameters.Lang))
                            {
                                Directory.CreateDirectory(wd);
                            }
                            else if (parameters.Lang == lang.Language)
                            {
                                wd = bindir;
                            }
                            else
                            {
                                continue;
                            }

                            foreach (var m in ac)
                            {
                                foreach (var itm in m.Assets)
                                {
                                    try
                                    {
                                        String fn = Path.Combine(wd, m.Info.Id, itm.Name.Replace("/", "\\"));
                                        Console.WriteLine("\tRendering {0}...", fn);
                                        if (!Directory.Exists(Path.GetDirectoryName(fn)))
                                        {
                                            Directory.CreateDirectory(Path.GetDirectoryName(fn));
                                        }
                                        File.WriteAllBytes(fn, ac.RenderAssetContent(itm, lang.Language));
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("E: {0}: {1} {2}", itm, e.GetType().Name, e);
                                        retVal = -1000;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(retVal);
        }
Ejemplo n.º 29
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);
            }
        }
Ejemplo n.º 30
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);
                    }
                }