Exemple #1
0
        /// <summary>
        /// Start the service
        /// </summary>
        public bool Start()
        {
            this.Starting?.Invoke(this, EventArgs.Empty);

            // Get configuration
            this.m_configuration      = ApplicationContext.Current.Configuration.GetSection <SynchronizationConfigurationSection>();
            this.m_threadPool         = ApplicationContext.Current.GetService <IThreadPoolService>();
            this.m_integrationService = ApplicationContext.Current.GetService <IClinicalIntegrationService>();
            this.m_networkInfoService = ApplicationContext.Current.GetService <INetworkInformationService>();

            this.m_networkInfoService.NetworkStatusChanged += (o, e) => this.Pull(SynchronizationPullTriggerType.OnNetworkChange);

            this.m_tracer.TraceInfo("Performing OnStart trigger pull...");
            this.Pull(SynchronizationPullTriggerType.OnStart);

            // Polling
            if (this.m_configuration.SynchronizationResources.Any(o => (o.Triggers & SynchronizationPullTriggerType.PeriodicPoll) != 0) &&
                this.m_configuration.PollInterval != default(TimeSpan))
            {
                Action <Object> pollFn = null;
                pollFn = _ =>
                {
                    this.Pull(SynchronizationPullTriggerType.PeriodicPoll);
                    ApplicationContext.Current.GetService <IThreadPoolService>().QueueUserWorkItem(this.m_configuration.PollInterval, pollFn, null);
                };
                ApplicationContext.Current.GetService <IThreadPoolService>().QueueUserWorkItem(this.m_configuration.PollInterval, pollFn, null);
            }
            this.Started?.Invoke(this, EventArgs.Empty);

            return(true);
        }
 /// <summary>
 /// Creates a new job
 /// </summary>
 public MailSynchronizationJob(IConfigurationManager configurationManager, IMailMessageRepositoryService mailRepositoryService, IJobStateManagerService jobStateManagerService, ISynchronizationLogService synchronizationLogService)
 {
     this.m_configuration             = configurationManager.GetSection <SynchronizationConfigurationSection>();
     this.m_securityConfiguration     = configurationManager.GetSection <SecurityConfigurationSection>();
     this.m_mailRepository            = mailRepositoryService;
     this.m_jobStateManager           = jobStateManagerService;
     this.m_synchronizationLogService = synchronizationLogService;
 }
Exemple #3
0
        public bool Save(String options)
        {
            // Demand the appropriate policy
            new PolicyPermission(PermissionState.Unrestricted, PolicyIdentifiers.AccessClientAdministrativeFunction).Demand();

            JObject optionObject = JsonConvert.DeserializeObject(options) as JObject;

            // Data mode
            switch (optionObject["data"]["mode"].Value <String>())
            {
            case "online":
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.RemoveAll(o => o == typeof(LocalPolicyInformationService).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(AmiPolicyInformationService).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(OAuthIdentityProvider).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(ImsiPersistenceService).AssemblyQualifiedName);
                break;

            case "offline":
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(LocalPersistenceService).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(LocalIdentityService).AssemblyQualifiedName);
                break;

            case "sync":
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(LocalPersistenceService).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(OAuthIdentityProvider).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(QueueManagerService).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(RemoteSynchronizationService).AssemblyQualifiedName);
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(ImsiIntegrationService).AssemblyQualifiedName);

                // Sync settings
                var syncConfig = new SynchronizationConfigurationSection();
                // TODO: Customize this
                foreach (var res in new String[] { "ConceptSet", "AssigningAuthority", "IdentifierType", "ExtensionType", "ConceptClass", "Concept", "Material", "Place", "Organization", "SecurityRole", "UserEntity", "Provider", "ManufacturedMaterial" })
                {
                    var syncSetting = new SynchronizationResource()
                    {
                        ResourceAqn = res,
                        Triggers    = SynchronizationPullTriggerType.Always
                    };

                    var efield = typeof(EntityClassKeys).GetField(res);
                    if (efield != null && res != "Place")
                    {
                        syncSetting.Filters.Add("classConcept=" + efield.GetValue(null).ToString());
                    }

                    syncConfig.SynchronizationResources.Add(syncSetting);
                }
                ApplicationContext.Current.Configuration.Sections.Add(syncConfig);
                break;
            }
            ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(LocalRoleProviderService).AssemblyQualifiedName);
            // Password hashing
            switch (optionObject["security"]["hasher"].Value <String>())
            {
            case "SHA256PasswordHasher":
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(SHA256PasswordHasher).AssemblyQualifiedName);
                break;

            case "SHAPasswordHasher":
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(SHAPasswordHasher).AssemblyQualifiedName);
                break;

            case "PlainTextPasswordHasher":
                ApplicationContext.Current.Configuration.GetSection <ApplicationConfigurationSection>().ServiceTypes.Add(typeof(PlainTextPasswordHasher).AssemblyQualifiedName);
                break;
            }

            // Proxy
            if (optionObject["network"]["useProxy"].Value <Boolean>())
            {
                ApplicationContext.Current.Configuration.GetSection <ServiceClientConfigurationSection>().ProxyAddress = optionObject["network"]["proxyAddress"].Value <String>();
            }

            // Log settings
            var logSettings = ApplicationContext.Current.Configuration.GetSection <DiagnosticsConfigurationSection>();

            logSettings.TraceWriter = new System.Collections.Generic.List <TraceWriterConfiguration>()
            {
#if DEBUG
                new TraceWriterConfiguration()
                {
                    Filter             = System.Diagnostics.Tracing.EventLevel.LogAlways,
                    InitializationData = "OpenIZ",
                    TraceWriter        = new LogTraceWriter(System.Diagnostics.Tracing.EventLevel.LogAlways, "OpenIZ")
                },
#endif
                new TraceWriterConfiguration()
                {
                    Filter             = (EventLevel)Enum.Parse(typeof(EventLevel), optionObject["log"]["mode"].Value <String>()),
                    InitializationData = "OpenIZ",
                    TraceWriter        = new FileTraceWriter((EventLevel)Enum.Parse(typeof(EventLevel), optionObject["log"]["mode"].Value <String>()), "OpenIZ")
                }
            };

            this.m_tracer.TraceInfo("Saving configuration options {0}", options);
            AndroidApplicationContext.Current.ConfigurationManager.Save();


            return(true);
        }
Exemple #4
0
        /// <summary>
        /// Start the service
        /// </summary>
        public bool Start()
        {
            this.Starting?.Invoke(this, EventArgs.Empty);

            // Get configuration
            this.m_configuration      = ApplicationContext.Current.Configuration.GetSection <SynchronizationConfigurationSection>();
            this.m_threadPool         = ApplicationContext.Current.GetService <IThreadPoolService>();
            this.m_integrationService = ApplicationContext.Current.GetService <IClinicalIntegrationService>();
            this.m_networkInfoService = ApplicationContext.Current.GetService <INetworkInformationService>();

            this.m_networkInfoService.NetworkStatusChanged += (o, e) => this.Pull(SynchronizationPullTriggerType.OnNetworkChange);

            // Notification for tickles when the pull is completed
            this.PullCompleted += (o, e) =>
            {
                if (e.Type == null) // general pull complete
                {
                    ApplicationContext.Current.SetProgress(Strings.locale_idle, 1.0f);
                    var tickleService = ApplicationContext.Current.GetService <ITickleService>();
                    if (e.IsInitial)
                    {
                        tickleService.SendTickle(
                            new Tickler.Tickle(Guid.Empty, Tickler.TickleType.Task | Tickler.TickleType.Toast, Strings.locale_sync_initial, DateTime.Now.Add(this.m_configuration.PollInterval))
                            );
                    }
                    else
                    {
                        tickleService.SendTickle(
                            new Tickler.Tickle(Guid.Empty, Tickler.TickleType.Task | Tickler.TickleType.Toast, Strings.locale_sync_complete, DateTime.Now.Add(this.m_configuration.PollInterval))
                            );
                    }
                }
            };

            ApplicationServiceContext.Current.Started += (xo, xe) =>
            {
                try
                {
                    this.m_tracer.TraceInfo("Performing OnStart trigger pull...");
                    this.Pull(SynchronizationPullTriggerType.OnStart);

                    // Polling
                    if (this.m_configuration.SynchronizationResources.Any(o => (o.Triggers & SynchronizationPullTriggerType.PeriodicPoll) != 0) &&
                        this.m_configuration.PollInterval != default(TimeSpan))
                    {
                        var jms  = ApplicationServiceContext.Current.GetService <IJobManagerService>();
                        var jsms = ApplicationServiceContext.Current.GetService <IJobStateManagerService>();
                        var job  = new RemoteSynchronizationJob(this, jsms);
                        jms.AddJob(job, JobStartType.DelayStart);
                        jms.SetJobSchedule(job, this.m_configuration.PollInterval);
                    }
                }
                catch (Exception)
                {
                    this.m_tracer.TraceError("Error starting remote sync service: {0}");
                }
            };

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

            return(true);
        }
        /// <summary>
        /// Start the daemon service
        /// </summary>
        public bool Start()
        {
            this.Starting?.Invoke(this, EventArgs.Empty);

            this.m_configuration         = ApplicationContext.Current.Configuration.GetSection <SynchronizationConfigurationSection>();
            this.m_securityConfiguration = ApplicationContext.Current.Configuration.GetSection <SecurityConfigurationSection>();

            // Application context has started
            ApplicationContext.Current.Started += (o, e) =>
            {
                try
                {
                    // We are to poll for alerts always (never push supported)
                    TimeSpan pollInterval = this.m_configuration.PollInterval == TimeSpan.MinValue ? new TimeSpan(0, 10, 0) : this.m_configuration.PollInterval;
                    this.m_alertRepository = ApplicationContext.Current.GetService <IAlertRepositoryService>();
                    Action <Object> pollAction = null;
                    pollAction = x =>
                    {
                        try
                        {
                            var amiClient = new AmiServiceClient(ApplicationContext.Current.GetRestClient("ami"));
                            amiClient.Client.Credentials = this.GetCredentials(amiClient.Client);
                            // Pull from alerts
                            if (!this.m_isRunning)
                            {
                                return;
                            }

                            // When was the last time we polled an alert?
                            var lastTime = SynchronizationLog.Current.GetLastTime(typeof(AlertMessage));

                            var syncTime = lastTime.HasValue ? new DateTimeOffset(lastTime.Value) : DateTimeOffset.Now.AddHours(-1);

                            // Poll action for all alerts to "everyone"
                            AmiCollection <AlertMessageInfo> serverAlerts = amiClient.GetAlerts(a => a.CreationTime >= lastTime && a.To.Contains("everyone"));


                            // TODO: We need to filter by users in which this tablet will be interested in

                            ParameterExpression userParameter = Expression.Parameter(typeof(SecurityUser), "u");
                            // User name filter
                            Expression userNameFilter = Expression.Equal(Expression.MakeMemberAccess(userParameter, userParameter.Type.GetRuntimeProperty("UserName")), Expression.Constant(this.m_securityConfiguration.DeviceName));

                            // Or eith other users which have logged into this tablet
                            foreach (var user in ApplicationContext.Current.GetService <IDataPersistenceService <SecurityUser> >().Query(u => u.LastLoginTime != null && u.UserName != this.m_securityConfiguration.DeviceName))
                            {
                                userNameFilter = Expression.OrElse(userNameFilter,
                                                                   Expression.Equal(Expression.MakeMemberAccess(userParameter, userParameter.Type.GetRuntimeProperty("UserName")), Expression.Constant(user.UserName))
                                                                   );
                            }

                            ParameterExpression parmExpr       = Expression.Parameter(typeof(AlertMessage), "a");
                            Expression          timeExpression = Expression.GreaterThanOrEqual(
                                Expression.Convert(Expression.MakeMemberAccess(parmExpr, parmExpr.Type.GetRuntimeProperty("CreationTime")), typeof(DateTimeOffset)),
                                Expression.Constant(syncTime)
                                ),
                            // this tablet expression
                                                userExpression = Expression.Call(
                                (MethodInfo)typeof(Enumerable).GetGenericMethod("Any", new Type[] { typeof(SecurityUser) }, new Type[] { typeof(IEnumerable <SecurityUser>), typeof(Func <SecurityUser, bool>) }),
                                Expression.MakeMemberAccess(parmExpr, parmExpr.Type.GetRuntimeProperty("RcptTo")),
                                Expression.Lambda <Func <SecurityUser, bool> >(userNameFilter, userParameter));

                            serverAlerts.CollectionItem = serverAlerts.CollectionItem.Union(amiClient.GetAlerts(Expression.Lambda <Func <AlertMessage, bool> >(Expression.AndAlso(timeExpression, userExpression), parmExpr)).CollectionItem).ToList();

                            // Import the alerts
                            foreach (var itm in serverAlerts.CollectionItem)
                            {
                                this.m_tracer.TraceVerbose("Importing ALERT: [{0}]: {1}", itm.AlertMessage.TimeStamp, itm.AlertMessage.Subject);
                                itm.AlertMessage.Body = String.Format("<pre>{0}</pre>", itm.AlertMessage.Body);
                                this.m_alertRepository.BroadcastAlert(itm.AlertMessage);
                            }

                            // Push alerts which I have created or updated
                            //int tc = 0;
                            //foreach(var itm in this.m_alertRepository.Find(a=> (a.TimeStamp >= lastTime ) && a.Flags != AlertMessageFlags.System, 0, null, out tc))
                            //{
                            //    if (!String.IsNullOrEmpty(itm.To))
                            //    {
                            //        this.m_tracer.TraceVerbose("Sending ALERT: [{0}]: {1}", itm.TimeStamp, itm.Subject);
                            //        if (itm.UpdatedTime != null)
                            //            amiClient.UpdateAlert(itm.Key.ToString(), new AlertMessageInfo(itm));
                            //        else
                            //            amiClient.CreateAlert(new AlertMessageInfo(itm));
                            //    }
                            //}

                            SynchronizationLog.Current.Save(typeof(AlertMessage), null, null, null);
                        }
                        catch (Exception ex)
                        {
                            this.m_tracer.TraceError("Could not pull alerts: {0}", ex.Message);
                        }
                        finally
                        {
                            // Re-schedule myself in the poll interval time
                            ApplicationContext.Current.GetService <IThreadPoolService>().QueueUserWorkItem(pollInterval, pollAction, null);
                        }
                    };

                    //ApplicationContext.Current.GetService<IThreadPoolService>().QueueUserWorkItem(pollInterval, pollAction, null);
                    this.m_isRunning = true;

                    pollAction(null);
                }
                catch (Exception ex)
                {
                    this.m_tracer.TraceError("Error starting Alert Sync: {0}", ex.Message);
                }
                //this.m_alertRepository.Committed +=
            };

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

            return(true);
        }