Exemplo n.º 1
0
        /// <summary>
        /// Determines whether the network is available.
        /// </summary>
        /// <returns>Returns true if the network is available.</returns>
        public bool IsAvailable()
        {
            try
            {
                //var restClient = ApplicationContext.Current.GetRestClient("imsi");
                var networkInformationService = ApplicationContext.Current.GetService <INetworkInformationService>();
                if (networkInformationService.IsNetworkAvailable)
                {
                    ImsiServiceClient client = this.GetServiceClient(); //new ImsiServiceClient(restClient);
                    client.Client.Credentials = new NullCredentials();
                    client.Client.Description.Endpoint[0].Timeout = 10000;

                    return(this.IsValidVersion(client) &&
                           client.Ping());
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError($"Unable to determine network state: {e}");
                return(false);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets a specified model.
        /// </summary>
        /// <typeparam name="TModel">The type of model data to retrieve.</typeparam>
        /// <param name="key">The key of the model.</param>
        /// <param name="versionKey">The version key of the model.</param>
        /// <param name="options">The integrations query options.</param>
        /// <returns>Returns a model.</returns>
        public TModel Get <TModel>(Guid key, Guid?versionKey, IntegrationQueryOptions options = null) where TModel : IdentifiedData
        {
            try
            {
                ImsiServiceClient client = this.GetServiceClient(); //new ImsiServiceClient(ApplicationContext.Current.GetRestClient("imsi"));
                client.Client.Requesting += IntegrationQueryOptions.CreateRequestingHandler(options);
                client.Client.Responding += (o, e) => this.Responding?.Invoke(o, e);
                client.Client.Credentials = this.GetCredentials(client.Client);
                if (client.Client.Credentials == null)
                {
                    return(null);
                }

                this.m_tracer.TraceVerbose("Performing IMSI GET ({0}):{1}v{2}", typeof(TModel).FullName, key, versionKey);
                var retVal = client.Get <TModel>(key, versionKey);

                if (retVal is Bundle)
                {
                    (retVal as Bundle)?.Reconstitute();
                    return((retVal as Bundle).Entry as TModel);
                }
                else
                {
                    return(retVal as TModel);
                }
            }
            catch (TargetInvocationException e)
            {
                throw Activator.CreateInstance(e.InnerException.GetType(), "Error performing action", e) as Exception;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Converts an <see cref="EditConceptModel"/> instance to a <see cref="Concept"/> instance.
        /// </summary>
        /// <param name="imsiServiceClient">The ImsiServiceClient instance.</param>
        /// <param name="concept">The concept.</param>
        /// <returns>Returns the converted concept instance.</returns>
        public Concept ToEditConceptModel(ImsiServiceClient imsiServiceClient, Concept concept)
        {
            concept.CreationTime = DateTimeOffset.Now;
            concept.VersionKey   = null;

            if (!string.Equals(this.ConceptClass, concept.ClassKey.ToString()))
            {
                concept.Class = new ConceptClass
                {
                    Key = Guid.Parse(this.ConceptClass)
                };
            }

            concept.Mnemonic = this.Mnemonic;

            if (string.IsNullOrWhiteSpace(AddReferenceTerm) || string.IsNullOrWhiteSpace(RelationshipType))
            {
                return(concept);
            }

            Guid id, relationshipKey;

            if (Guid.TryParse(AddReferenceTerm, out id) && Guid.TryParse(RelationshipType, out relationshipKey))
            {
                var term = imsiServiceClient.Get <ReferenceTerm>(id, null) as ReferenceTerm;
                if (term != null)
                {
                    concept.ReferenceTerms.Add(new ConceptReferenceTerm(term.Key, relationshipKey));
                }
            }

            return(concept);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Finds the specified model
        /// </summary>
        public Bundle Find <TModel>(Expression <Func <TModel, bool> > predicate, int offset, int?count, IntegrationQueryOptions options = null) where TModel : IdentifiedData
        {
            try
            {
                ImsiServiceClient client = this.GetServiceClient();
                client.Client.Requesting += IntegrationQueryOptions.CreateRequestingHandler(options);
                client.Client.Responding += (o, e) => this.Responding?.Invoke(o, e);
                client.Client.Credentials = this.GetCredentials(client.Client);
                if (client.Client.Credentials == null)
                {
                    return(null);
                }
                if (options?.Timeout.HasValue == true)
                {
                    client.Client.Description.Endpoint[0].Timeout = options.Timeout.Value;
                }

                this.m_tracer.TraceVerbose("Performing IMSI query ({0}):{1}", typeof(TModel).FullName, predicate);

                var retVal = client.Query <TModel>(predicate, offset, count, queryId: options?.QueryId);
                //retVal?.Reconstitute();
                return(retVal);
            }
            catch (TargetInvocationException e)
            {
                throw Activator.CreateInstance(e.InnerException.GetType(), "Error performing action", e) as Exception;
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Inserts specified data.
        /// </summary>
        /// <param name="data">The data to be inserted.</param>
        public void Insert(IdentifiedData data)
        {
            try
            {
                if (!(data is Bundle || data is Entity || data is Act))
                {
                    return;
                }

                if (data is Bundle)
                {
                    data.Key = null;
                }

                ImsiServiceClient client = this.GetServiceClient(); //new ImsiServiceClient(ApplicationContext.Current.GetRestClient("imsi"));
                client.Client.Credentials = this.GetCredentials(client.Client);
                client.Client.Responding += (o, e) => this.Responding?.Invoke(o, e);
                if (client.Client.Credentials == null)
                {
                    return;
                }

                // Special case = Batch submit of data with an entry point
                var submission = (data as Bundle)?.Entry ?? data;
                client.Client.Requesting += (o, e) =>
                {
                    var bund = e.Body as Bundle;
                    if (!(bund?.Entry is UserEntity))                                                // not submitting a user entity so we only submit ACT
                    {
                        bund?.Item.RemoveAll(i => !(i is Act || i is Person && !(i is UserEntity))); // || i is EntityRelationship));
                    }
                    if (bund != null)
                    {
                        bund.Key = Guid.NewGuid();
                        e.Cancel = bund.Item.Count == 0;
                    }
                };

                // Create method
                var method = typeof(ImsiServiceClient).GetRuntimeMethods().FirstOrDefault(o => o.Name == "Create" && o.GetParameters().Length == 1);
                method = method.MakeGenericMethod(new Type[] { submission.GetType() });

                this.m_tracer.TraceVerbose("Performing IMSI INSERT {0}", submission);
                var iver = method.Invoke(client, new object[] { submission }) as IVersionedEntity;

                if (iver != null)
                {
                    this.UpdateToServerCopy(iver);
                }
            }
            catch (TargetInvocationException e)
            {
                throw Activator.CreateInstance(e.InnerException.GetType(), "Error performing action", e.InnerException) as Exception;
            }
        }
Exemplo n.º 6
0
 public GenericImsiPersister()
 {
     this.m_client = new ImsiServiceClient(ApplicationContext.Current.GetRestClient("imsi"));
     this.m_client.Client.Requesting += (o, e) =>
     {
         e.Query.Add("_expand", new List <String>()
         {
             "typeConcept",
             "address.use",
             "name.use"
         });
     };
 }
Exemplo n.º 7
0
        /// <summary>
        /// Get service client
        /// </summary>
        private ImsiServiceClient GetServiceClient()
        {
            var retVal = new ImsiServiceClient(ApplicationContext.Current.GetRestClient("imsi"));

            retVal.Client.Accept      = "application/xml";
            retVal.Client.Requesting += (o, e) =>
            {
                if (AuthenticationContext.CurrentUIContext.Principal != AuthenticationContext.AnonymousPrincipal &&
                    AuthenticationContext.CurrentUIContext.Principal != AuthenticationContext.Current.Principal)
                {
                    e.AdditionalHeaders["X-OpenIZ-OnBehalfOf"] = AuthenticationContext.CurrentUIContext.Principal.Identity.Name;
                }
            };
            return(retVal);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Called when the action is executing.
        /// </summary>
        /// <param name="filterContext">The filter context of the action executing.</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var amiRestClient = new RestClientService(Constants.Ami)
            {
                Accept      = Constants.ApplicationXml,
                Credentials = new AmiCredentials(this.User, HttpContext.Request)
            };

            this.AmiClient = new AmiServiceClient(amiRestClient);

            var imsiRestClient = new RestClientService(Constants.Imsi)
            {
                Accept      = Constants.ApplicationXml,
                Credentials = new ImsCredentials(this.User, HttpContext.Request)
            };

            this.ImsiClient = new ImsiServiceClient(imsiRestClient);

            base.OnActionExecuting(filterContext);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Obsoletes specified data.
        /// </summary>
        /// <param name="data">The data to be obsoleted.</param>
        public void Obsolete(IdentifiedData data, bool unsafeObsolete = false)
        {
            try
            {
                if (!(data is Bundle || data is Entity || data is Act || data is EntityRelationship)) // || data is EntityRelationship))
                {
                    return;
                }

                ImsiServiceClient client = this.GetServiceClient(); //new ImsiServiceClient(ApplicationContext.Current.GetRestClient("imsi"));
                client.Client.Credentials = this.GetCredentials(client.Client);
                client.Client.Responding += (o, e) => this.Responding?.Invoke(o, e);
                if (client.Client.Credentials == null)
                {
                    return;
                }
                // Force an update
                if (unsafeObsolete)
                {
                    client.Client.Requesting += (o, e) => e.AdditionalHeaders["X-OpenIZ-Unsafe"] = "true";
                }
                else
                {
                    client.Client.Requesting += (o, e) => e.AdditionalHeaders["If-Match"] = data.Tag;
                }

                var method = typeof(ImsiServiceClient).GetRuntimeMethods().FirstOrDefault(o => o.Name == "Obsolete" && o.GetParameters().Length == 1);
                method = method.MakeGenericMethod(new Type[] { data.GetType() });
                this.m_tracer.TraceVerbose("Performing IMSI OBSOLETE {0}", data);

                var iver = method.Invoke(client, new object[] { data }) as IVersionedEntity;
                if (iver != null)
                {
                    this.UpdateToServerCopy(iver);
                }
            }
            catch (TargetInvocationException e)
            {
                throw Activator.CreateInstance(e.InnerException.GetType(), "Error performing action", e) as Exception;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Throws an exception if the specified service client has the invalid version
        /// </summary>
        private bool IsValidVersion(ImsiServiceClient client)
        {
            var expectedVersion = typeof(IdentifiedData).GetTypeInfo().Assembly.GetName().Version;

            if (this.m_options == null)
            {
                this.m_options = client.Options();
            }
            if (this.m_options == null)
            {
                return(false);
            }
            var version = new Version(this.m_options.InterfaceVersion);

            // Major version must match & minor version must match. Example:
            // Server           Client          Result
            // 0.6.14.*         0.6.14.*        Compatible
            // 0.7.0.*          0.6.14.*        Not compatible (server newer)
            // 0.7.0.*          0.9.0.0         Compatible (client newer)
            // 0.8.0.*          1.0.0.0         Not compatible (major version mis-match)
            this.m_tracer.TraceVerbose("IMSI server indicates version {0}", this.m_options.InterfaceVersion);
            return(version < expectedVersion);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityRelationshipService" /> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="conceptService">The concept service.</param>
 public EntityRelationshipService(ImsiServiceClient client, IConceptService conceptService, IEntityService entityService) : base(client)
 {
     this.conceptService = conceptService;
     this.entityService  = entityService;
 }
Exemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImsiServerInformationService"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 public ImsiServerInformationService(ImsiServiceClient client) : base(client)
 {
 }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PlaceConceptService"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="conceptService">The concept service.</param>
 public PlaceConceptService(ImsiServiceClient client, IConceptService conceptService) : base(client)
 {
     this.conceptService = conceptService;
 }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MaterialConceptService"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="cacheService">The cache service.</param>
 /// <param name="conceptService">The concept service.</param>
 public MaterialConceptService(ImsiServiceClient client, ICacheService cacheService, IConceptService conceptService) : base(client)
 {
     this.cacheService   = cacheService;
     this.conceptService = conceptService;
 }
Exemplo n.º 15
0
        /// <summary>
        /// Updates specified data.
        /// </summary>
        /// <param name="data">The data to be updated.</param>
        public void Update(IdentifiedData data, bool unsafeUpdate = false)
        {
            try
            {
                // HACK
                if (!(data is Bundle || data is Entity || data is Act || data is Patch))
                {
                    return;
                }
                if (data is Patch &&
                    !typeof(Entity).GetTypeInfo().IsAssignableFrom((data as Patch).AppliesTo.Type.GetTypeInfo()) &&
                    !typeof(Act).GetTypeInfo().IsAssignableFrom((data as Patch).AppliesTo.Type.GetTypeInfo()))
                {
                    return;
                }

                ImsiServiceClient client = this.GetServiceClient(); //new ImsiServiceClient(ApplicationContext.Current.GetRestClient("imsi"));
                client.Client.Credentials = this.GetCredentials(client.Client);
                client.Client.Responding += (o, e) => this.Responding?.Invoke(o, e);
                if (client.Client.Credentials == null)
                {
                    return;
                }

                // Force an update
                if (unsafeUpdate)
                {
                    client.Client.Requesting += (o, e) => e.AdditionalHeaders["X-Patch-Force"] = "true";
                }

                // Special case = Batch submit of data with an entry point
                var submission = (data as Bundle)?.Entry ?? data;

                // Assign a uuid for this submission
                if (data is Bundle && data.Key == null)
                {
                    data.Key = Guid.NewGuid();
                }

                if (submission is Patch)
                {
                    var patch = submission as Patch;

                    // Patch for update on times (obsolete, creation time, etc. always fail so lets remove them)
                    patch.Operation.RemoveAll(o => o.OperationType == PatchOperationType.Test && this.m_removePatchTest.Contains(o.Path));
                    this.m_tracer.TraceVerbose("Performing IMSI UPDATE (PATCH) {0}", patch);

                    var existingKey = patch.AppliesTo.Key;
                    // Get the object and then update
                    var  idp        = typeof(IDataPersistenceService <>).MakeGenericType(patch.AppliesTo.Type);
                    var  idpService = ApplicationContext.Current.GetService(idp);
                    var  getMethod  = idp.GetRuntimeMethod("Get", new Type[] { typeof(Guid) });
                    var  existing   = getMethod.Invoke(idpService, new object[] { existingKey }) as IdentifiedData;
                    Guid newUuid    = Guid.Empty;

                    try
                    {
                        newUuid = client.Patch(patch);

                        // Update the server version key
                        if (existing is IVersionedEntity &&
                            (existing as IVersionedEntity)?.VersionKey != newUuid)
                        {
                            this.m_tracer.TraceVerbose("Patch successful - VersionId of {0} to {1}", existing, newUuid);
                            (existing as IVersionedEntity).VersionKey = newUuid;
                            var updateMethod = idp.GetRuntimeMethod("Update", new Type[] { getMethod.ReturnType });
                            updateMethod.Invoke(idpService, new object[] { existing });
                        }
                    }
                    catch (WebException e)
                    {
                        switch ((e.Response as HttpWebResponse).StatusCode)
                        {
                        case HttpStatusCode.Conflict:     // Try to resolve the conflict in an automated way
                            this.m_tracer.TraceWarning("Will attempt to force PATCH {0}", patch);

                            // Condition 1: Can we apply the patch without causing any issues (ignoring version)
                            client.Client.Requesting += (o, evt) =>
                            {
                                evt.AdditionalHeaders["X-Patch-Force"] = "true";
                            };

                            // Configuration dictates only safe patch
                            if (ApplicationContext.Current.Configuration.GetSection <SynchronizationConfigurationSection>().SafePatchOnly)
                            {
                                // First, let's grab the item
                                var serverCopy = this.Get(patch.AppliesTo.Type, patch.AppliesTo.Key.Value, null);
                                if (ApplicationContext.Current.GetService <IPatchService>().Test(patch, serverCopy))
                                {
                                    newUuid = client.Patch(patch);
                                }
                                else
                                {
                                    // There are no intersections of properties between the object we have and the server copy
                                    var serverDiff = ApplicationContext.Current.GetService <IPatchService>().Diff(existing, serverCopy);
                                    if (!serverDiff.Operation.Any(sd => patch.Operation.Any(po => po.Path == sd.Path && sd.OperationType != PatchOperationType.Test)))
                                    {
                                        newUuid = client.Patch(patch);
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                            else     /// unsafe patch ... meh
                            {
                                newUuid = client.Patch(patch);
                            }
                            break;

                        case HttpStatusCode.NotFound:     // We tried to update something that doesn't exist on the server? That's odd
                            this.m_tracer.TraceWarning("Server reported patch target doesn't exist! {0}", patch);
                            var svcType            = typeof(IDataPersistenceService <>).MakeGenericType(patch.AppliesTo.Type);
                            var persistenceService = ApplicationContext.Current.GetService(svcType) as IDataPersistenceService;
                            var localObject        = persistenceService.Get(patch.AppliesTo.Key.Value);

                            // Re-queue for create
                            // First, we have to remove the "replaces version" key as it doesn't make much sense
                            if (localObject is IVersionedEntity)
                            {
                                (localObject as IVersionedEntity).PreviousVersionKey = null;
                            }
                            this.Insert(Bundle.CreateBundle(localObject as IdentifiedData));
                            break;
                        }
                    }

                    // Update the server version key
                    if (existing is IVersionedEntity &&
                        (existing as IVersionedEntity)?.VersionKey != newUuid)
                    {
                        this.m_tracer.TraceVerbose("Patch successful - VersionId of {0} to {1}", existing, newUuid);
                        (existing as IVersionedEntity).VersionKey = newUuid;
                        var updateMethod = idp.GetRuntimeMethod("Update", new Type[] { getMethod.ReturnType });
                        updateMethod.Invoke(idpService, new object[] { existing });
                    }
                }
                else // regular update
                {
                    // Force an update
                    if (!unsafeUpdate)
                    {
                        client.Client.Requesting += (o, e) => e.AdditionalHeaders["If-Match"] = data.Tag;
                    }

                    client.Client.Requesting += (o, e) => (e.Body as Bundle)?.Item.RemoveAll(i => !(i is Act || i is Patient || i is Provider || i is UserEntity)); // || i is EntityRelationship));

                    var method = typeof(ImsiServiceClient).GetRuntimeMethods().FirstOrDefault(o => o.Name == "Update" && o.GetParameters().Length == 1);
                    method = method.MakeGenericMethod(new Type[] { submission.GetType() });
                    this.m_tracer.TraceVerbose("Performing IMSI UPDATE (FULL) {0}", data);

                    var iver = method.Invoke(client, new object[] { submission }) as IVersionedEntity;
                    if (iver != null)
                    {
                        this.UpdateToServerCopy(iver);
                    }
                }
            }
            catch (TargetInvocationException e)
            {
                throw Activator.CreateInstance(e.InnerException.GetType(), "Error performing action", e) as Exception;
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConceptService" /> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="cacheService">The cache service.</param>
 public ConceptService(ImsiServiceClient client, ICacheService cacheService) : base(client)
 {
     this.cacheService = cacheService;
 }
Exemplo n.º 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityService" /> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="conceptService">The concept service.</param>
 /// <param name="coreAuditService">The core audit service.</param>
 /// <param name="entityAuditService">The entity audit service.</param>
 public EntityService(ImsiServiceClient client, IConceptService conceptService, ICoreAuditService coreAuditService, IEntityAuditService entityAuditService) : base(client)
 {
     this.conceptService     = conceptService;
     this.coreAuditService   = coreAuditService;
     this.entityAuditService = entityAuditService;
 }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImsiServiceBase"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 protected ImsiServiceBase(ImsiServiceClient client)
 {
     this.Client = client;
 }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserService"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 public UserService(ImsiServiceClient client) : base(client)
 {
 }