예제 #1
0
        /// <summary>
        /// Simplifies an HDSI object
        /// </summary>
        public static ExpandoObject ToViewModel(IdentifiedData data)
        {
            try
            {
                // Serialize to a view model serializer
                using (MemoryStream ms = new MemoryStream())
                {
                    using (TextWriter tw = new StreamWriter(ms, Encoding.UTF8, 2048, true))
                        using (var szr = new JsonViewModelSerializer())
                        {
                            szr.LoadSerializerAssembly(typeof(SecurityApplicationViewModelSerializer).Assembly);
                            szr.Serialize(tw, data);
                        }

                    ms.Seek(0, SeekOrigin.Begin);

                    // Parse
                    JsonSerializer jsz = new JsonSerializer()
                    {
                        DateFormatHandling = DateFormatHandling.IsoDateFormat, TypeNameHandling = TypeNameHandling.None
                    };
                    using (JsonReader reader = new JsonTextReader(new StreamReader(ms)))
                    {
                        var retVal = jsz.Deserialize <Newtonsoft.Json.Linq.JObject>(reader);
                        return(ConvertToJint(retVal));
                    }
                }
            }
            catch (Exception e)
            {
                throw new JsonSerializationException($"Error converting {data} to view model", e);
            }
        }
예제 #2
0
        /// <summary>
        /// Serialize patch
        /// </summary>
        private Patch SerializePatch(Patch patch)
        {
            String patchXml = String.Empty;
            Patch  retVal   = null;

            using (StringWriter sw = new StringWriter())
            {
                var xsz = new XmlSerializer(typeof(Patch));
                xsz.Serialize(sw, patch);
                patchXml = sw.ToString();
            }
            using (StringReader sr = new StringReader(patchXml))
            {
                var xsz = new XmlSerializer(typeof(Patch));
                retVal = xsz.Deserialize(sr) as Patch;
            }
            var    jser      = new JsonViewModelSerializer();
            string patchJson = JsonConvert.SerializeObject(patch, Formatting.Indented, new JsonSerializerSettings()
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                NullValueHandling  = NullValueHandling.Ignore,
                TypeNameHandling   = TypeNameHandling.Auto,
                Binder             = new ModelSerializationBinder()
            });

            return(retVal);
        }
예제 #3
0
        public void TestSerializeComplexIMSObject()
        {
            var serializer = new JsonViewModelSerializer();
            var json       = serializer.Serialize(this.m_patientUnderTest);

            Assert.IsNotNull(json);
        }
예제 #4
0
        public void ShouldHandlePartials()
        {
            SimpleCarePlanService scp = new SimpleCarePlanService();

            ApplicationServiceContext.Current = this;
            // Patient that is just born = Schedule OPV
            Patient newborn = new Patient()
            {
                Key           = Guid.NewGuid(),
                DateOfBirth   = DateTime.Now,
                GenderConcept = new Core.Model.DataTypes.Concept()
                {
                    Mnemonic = "FEMALE"
                }
            };

            // Now apply the protocol
            var    acts           = scp.CreateCarePlan(newborn);
            var    jsonSerializer = new JsonViewModelSerializer();
            String json           = jsonSerializer.Serialize(newborn);

            Assert.AreEqual(83, acts.Action.Count());
            Assert.IsFalse(acts.Action.Any(o => o.Protocols.Count() > 1));
            acts = scp.CreateCarePlan(newborn);
            //Assert.AreEqual(60, acts.Action.Count());
            acts.Action.RemoveAll(o => o is QuantityObservation);
            Assert.AreEqual(23, acts.Action.Count);
            acts = scp.CreateCarePlan(newborn);
            //Assert.AreEqual(60, acts.Action.Count());
            Assert.AreEqual(83, acts.Action.Count());
            Assert.IsFalse(acts.Action.Any(o => !o.Participations.Any(p => p.ParticipationRoleKey == ActParticipationKey.RecordTarget)));
        }
예제 #5
0
        /// <summary>
        /// Expand the view model object to an identified object
        /// </summary>
        public static IdentifiedData ToModel(Object data)
        {
            try
            {
                var dictData = data as IDictionary <String, object>;
                //if (dictData?.ContainsKey("$item") == true) // HACK: JInt does not like Item property on ExpandoObject
                //{
                //    dictData.Add("item", dictData["$item"]);
                //    dictData.Remove("$item");
                //}

                // Serialize to a view model serializer
                using (MemoryStream ms = new MemoryStream())
                {
                    JsonSerializer jsz = new JsonSerializer();
                    using (JsonWriter reader = new JsonTextWriter(new StreamWriter(ms, Encoding.UTF8, 2048, true)))
                        jsz.Serialize(reader, data);

                    // De-serialize
                    ms.Seek(0, SeekOrigin.Begin);

                    using (var szr = new JsonViewModelSerializer())
                    {
                        szr.LoadSerializerAssembly(typeof(SecurityApplicationViewModelSerializer).Assembly);
                        return(szr.DeSerialize <IdentifiedData>(ms));
                    }
                }
            }
            catch (Exception e)
            {
                throw new JsonSerializationException("Error serializing object", e);
            }
        }
예제 #6
0
        public void TestSerializeActWithRelationships()
        {
            var act = new Act
            {
                ClassConcept = new Concept
                {
                    Key = ActClassKeys.Encounter
                },
                CreationTime = DateTimeOffset.Now,
                Key          = Guid.NewGuid(),
                MoodConcept  = new Concept
                {
                    Key = ActMoodKeys.Eventoccurrence
                },
                Relationships = new List <ActRelationship>
                {
                    new ActRelationship
                    {
                        RelationshipType = new Concept
                        {
                            Key      = ActRelationshipTypeKeys.HasSubject,
                            Mnemonic = "HasSubject"
                        },
                        TargetAct = new Act
                        {
                            Participations = new List <ActParticipation>
                            {
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.RecordTarget,
                                        Mnemonic = "RecordTarget"
                                    },
                                    PlayerEntity = this.m_patientUnderTest
                                },
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.Location,
                                        Mnemonic = "Location"
                                    },
                                    PlayerEntity = new Place
                                    {
                                        Key = Guid.Parse("AE2795E7-C40A-41CF-B77D-855EE2C3BF47")
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var serializer = new JsonViewModelSerializer();
            var actual     = serializer.Serialize(act);

            Assert.IsTrue(actual.Contains(ActMoodKeys.Eventoccurrence.ToString()));
            Assert.IsTrue(actual.Contains(ActClassKeys.Encounter.ToString()));
        }
예제 #7
0
        /// <summary>
        /// Create the specified serializer
        /// </summary>
        private JsonViewModelSerializer CreateSerializer(ViewModelDescription viewModelDescription)
        {
            var retVal = new JsonViewModelSerializer();

            retVal.ViewModel = viewModelDescription ?? this.m_defaultViewModel;
            retVal.LoadSerializerAssembly(typeof(OpenIZ.Core.Model.Json.Formatter.ActExtensionViewModelSerializer).Assembly);
            return(retVal);
        }
예제 #8
0
        public void TestShouldSkipWeight()
        {
            ProtocolDefinition  definition = ProtocolDefinition.Load(typeof(TestProtocolApply).Assembly.GetManifestResourceStream("SanteDB.Cdss.Xml.Test.Protocols.Weight.xml"));
            XmlClinicalProtocol xmlCp      = new XmlClinicalProtocol(definition);

            // Patient that is just born = Schedule OPV
            Patient newborn = new Patient()
            {
                Key           = Guid.NewGuid(),
                DateOfBirth   = DateTime.Now,
                GenderConcept = new Core.Model.DataTypes.Concept()
                {
                    Mnemonic = "FEMALE"
                },
                Participations = new List <ActParticipation>()
                {
                    new ActParticipation()
                    {
                        ParticipationRole = new Core.Model.DataTypes.Concept()
                        {
                            Mnemonic = "RecordTarget"
                        },
                        Act = new QuantityObservation()
                        {
                            Value       = (decimal)3.2,
                            TypeConcept = new Core.Model.DataTypes.Concept()
                            {
                                Mnemonic = "VitalSign-Weight"
                            },
                            ActTime = DateTime.Now
                        }
                    },
                    new ActParticipation()
                    {
                        ParticipationRole = new Core.Model.DataTypes.Concept()
                        {
                            Mnemonic = "RecordTarget"
                        },
                        Act = new PatientEncounter()
                        {
                            ActTime = DateTime.Now
                        }
                    }
                }
            };

            // Now apply the protocol
            var    acts           = xmlCp.Calculate(newborn, null);
            var    jsonSerializer = new JsonViewModelSerializer();
            String json           = jsonSerializer.Serialize(newborn);

            Assert.AreEqual(59, acts.Count);
        }
예제 #9
0
        public void DumpScopeView(String path)
        {
            var obj = this.GetScopeObject(this.m_scopeObject, path);
            JsonViewModelSerializer xsz = new JsonViewModelSerializer();

            using (var jv = new JsonTextWriter(Console.Out)
            {
                Formatting = Newtonsoft.Json.Formatting.Indented
            })
            {
                xsz.Serialize(jv, obj as IdentifiedData);
            }
            Console.WriteLine();
        }
예제 #10
0
        public void TestShouldNotRecurse()
        {
            var serializer = new JsonViewModelSerializer();
            var patient    = this.m_patientUnderTest.Clone() as Patient;

            patient.Relationships.Add(new EntityRelationship()
            {
                RelationshipType = new Concept()
                {
                    Key      = EntityRelationshipTypeKeys.Mother,
                    Mnemonic = "Mother"
                },
                TargetEntity = patient
            });
            var json = serializer.Serialize(this.m_patientUnderTest);

            Assert.IsNotNull(json);
            Assert.IsTrue(json.Contains("$ref"));
        }
예제 #11
0
        /// <summary>
        /// Create dataset
        /// </summary>
        public Stream CreateDataset(Stream datasetSource)
        {
            Bundle  input  = new JsonViewModelSerializer().DeSerialize(datasetSource, typeof(Bundle)) as Bundle;
            Dataset output = new Dataset("Generated Dataset");

            output.Action = input.Item.Select(i => new DataUpdate()
            {
                InsertIfNotExists = true,
                Element           = i
            }).OfType <DataInstallAction>().ToList();

            RestOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
            RestOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=codesystem.dataset";

            MemoryStream ms = new MemoryStream();

            XmlModelSerializerFactory.Current.CreateSerializer(typeof(Dataset)).Serialize(ms, output);
            ms.Seek(0, SeekOrigin.Begin);
            return(ms);
        }
예제 #12
0
        public void TestShouldScheduleOPV()
        {
            ProtocolDefinition  definition = ProtocolDefinition.Load(typeof(TestProtocolApply).Assembly.GetManifestResourceStream("SanteDB.Cdss.Xml.Test.Protocols.OralPolioVaccine.xml"));
            XmlClinicalProtocol xmlCp      = new XmlClinicalProtocol(definition);

            // Patient that is just born = Schedule OPV
            Patient newborn = new Patient()
            {
                Key           = Guid.NewGuid(),
                DateOfBirth   = DateTime.Now,
                GenderConcept = new Core.Model.DataTypes.Concept()
                {
                    Mnemonic = "FEMALE"
                }
            };
            // Now apply the protocol
            var    acts           = xmlCp.Calculate(newborn, new Dictionary <String, Object>());
            var    jsonSerializer = new JsonViewModelSerializer();
            String json           = jsonSerializer.Serialize(newborn);

            Assert.AreEqual(4, acts.Count);
        }
예제 #13
0
        public void TestSerializeSimpleAct()
        {
            var act = new Act
            {
                ClassConcept = new Concept
                {
                    Key = ActClassKeys.Encounter
                },
                CreationTime = DateTimeOffset.Now,
                Key          = Guid.NewGuid(),
                MoodConcept  = new Concept
                {
                    Key = ActMoodKeys.Eventoccurrence
                }
            };

            var serializer = new JsonViewModelSerializer();
            var actual     = serializer.Serialize(act);

            Assert.IsTrue(actual.Contains(ActMoodKeys.Eventoccurrence.ToString()));
            Assert.IsTrue(actual.Contains(ActClassKeys.Encounter.ToString()));
        }
예제 #14
0
 public void DumpLocalsJson(String id, String path)
 {
     this.ThrowIfNotDebugging();
     // Locals?
     if (id == null)
     {
         this.DumpObject(this.m_currentDebug.Locals, path);
     }
     else
     {
         var kobj = this.m_currentDebug.Locals[id];
         try
         {
             JavascriptExecutorPool.Current.ExecuteGlobal(e => kobj = e.Engine.GetValue(kobj));
             if (kobj.IsObject())
             {
                 Object obj = new Dictionary <String, Object>((kobj.AsObject() as ObjectWrapper).Target as ExpandoObject);
                 obj = SanteDB.BusinessRules.JavaScript.Util.JavascriptUtils.ToModel(this.GetScopeObject(obj, path));
                 JsonViewModelSerializer xsz = new JsonViewModelSerializer();
                 using (var jv = new JsonTextWriter(Console.Out)
                 {
                     Formatting = Newtonsoft.Json.Formatting.Indented
                 })
                 {
                     xsz.Serialize(jv, obj as IdentifiedData);
                 }
                 Console.WriteLine();
             }
             else
             {
                 this.DumpObject(kobj?.AsArray() ?? kobj?.AsObject(), path);
             }
         }
         catch
         {
             this.DumpObject(kobj?.AsObject()?.GetOwnProperties(), path);
         }
     }
 }
예제 #15
0
        public void TestShouldScheduleDTP()
        {
            ProtocolDefinition  definition = ProtocolDefinition.Load(typeof(TestProtocolApply).Assembly.GetManifestResourceStream("OpenIZ.Protocol.Xml.Test.Protocols.DTP-HepB-HibTrivalent.xml"));
            XmlClinicalProtocol xmlCp      = new XmlClinicalProtocol(definition);

            // Patient that is just born = Schedule OPV
            Patient newborn = new Patient()
            {
                Key           = Guid.NewGuid(),
                DateOfBirth   = DateTime.Now,
                GenderConcept = new Core.Model.DataTypes.Concept()
                {
                    Mnemonic = "FEMALE"
                }
            };

            // Now apply the protocol
            var    acts           = xmlCp.Calculate(newborn, null);
            var    jsonSerializer = new JsonViewModelSerializer();
            String json           = jsonSerializer.Serialize(newborn);

            Assert.AreEqual(3, acts.Count);
        }
예제 #16
0
        public void ShouldExcludeAdults()
        {
            SimpleCarePlanService scp = new SimpleCarePlanService();

            ApplicationServiceContext.Current = this;
            // Patient that is just born = Schedule OPV
            Patient adult = new Patient()
            {
                Key           = Guid.NewGuid(),
                DateOfBirth   = DateTime.Now.AddMonths(-240),
                GenderConcept = new Core.Model.DataTypes.Concept()
                {
                    Mnemonic = "FEMALE"
                }
            };

            // Now apply the protocol
            var    acts           = scp.CreateCarePlan(adult);
            var    jsonSerializer = new JsonViewModelSerializer();
            String json           = jsonSerializer.Serialize(adult);

            Assert.AreEqual(0, acts.Action.Count());
        }
예제 #17
0
        public void ShouldScheduleAppointments()
        {
            SimpleCarePlanService scp = new SimpleCarePlanService();

            ApplicationServiceContext.Current = this;
            // Patient that is just born = Schedule OPV
            Patient newborn = new Patient()
            {
                Key           = Guid.NewGuid(),
                DateOfBirth   = DateTime.Now,
                GenderConcept = new Core.Model.DataTypes.Concept()
                {
                    Mnemonic = "FEMALE"
                }
            };

            // Now apply the protocol
            var    acts           = scp.CreateCarePlan(newborn, true);
            var    jsonSerializer = new JsonViewModelSerializer();
            string json           = jsonSerializer.Serialize(newborn);

            Assert.AreEqual(60, acts.Action.Count());
            Assert.IsFalse(acts.Action.Any(o => o.Protocols.Count() > 1));
        }
예제 #18
0
        public void TestShouldAdhereToClassifierCodes()
        {
            AssigningAuthority aa = new AssigningAuthority()
            {
                Name       = "Ontario Health Insurance Card",
                DomainName = "OHIPCARD",
                Oid        = "1.2.3.4.5.67"
            };
            var aaPersistence = ApplicationContext.Current.GetService <IDataPersistenceService <AssigningAuthority> >();
            var ohipAuth      = aaPersistence.Insert(aa, s_authorization, TransactionMode.Commit);

            Patient p = new Patient()
            {
                StatusConcept = new Concept()
                {
                    Mnemonic = "ACTIVE"
                },
                Names = new List <EntityName>()
                {
                    new EntityName()
                    {
                        NameUse = new Concept()
                        {
                            Mnemonic = "OfficialRecord"
                        },
                        Component = new List <EntityNameComponent>()
                        {
                            new EntityNameComponent()
                            {
                                ComponentType = new Concept()
                                {
                                    Mnemonic = "Family"
                                },
                                Value = "Johnson"
                            },
                            new EntityNameComponent()
                            {
                                ComponentType = new Concept()
                                {
                                    Mnemonic = "Given"
                                },
                                Value = "William"
                            },
                            new EntityNameComponent()
                            {
                                ComponentType = new Concept()
                                {
                                    Mnemonic = "Given"
                                },
                                Value = "P."
                            },
                            new EntityNameComponent()
                            {
                                ComponentType = new Concept()
                                {
                                    Mnemonic = "Given"
                                },
                                Value = "Bear"
                            }
                        }
                    }
                },
                Identifiers = new List <EntityIdentifier>()
                {
                    new EntityIdentifier(
                        new AssigningAuthority()
                    {
                        DomainName = "OHIPCARD"
                    }, "12343120423")
                },
                Tags = new List <EntityTag>()
                {
                    new EntityTag("hasBirthCertificate", "true")
                },
                Extensions = new List <EntityExtension>()
                {
                    new EntityExtension()
                    {
                        ExtensionType = new ExtensionType()
                        {
                            Name             = "http://openiz.org/oiz/birthcertificate",
                            ExtensionHandler = typeof(EntityPersistenceServiceTest)
                        },
                        ExtensionValueXml = new byte[] { 1 }
                    }
                },
                GenderConcept = new Concept()
                {
                    Mnemonic = "Male"
                },
                DateOfBirth           = new DateTime(1984, 03, 22),
                MultipleBirthOrder    = 2,
                DeceasedDate          = new DateTime(2016, 05, 02),
                DeceasedDatePrecision = DatePrecision.Day,
                DateOfBirthPrecision  = DatePrecision.Day
            };

            var afterInsert = base.DoTestInsert(p, s_authorization);

            Assert.AreEqual("Male", afterInsert.GenderConcept.Mnemonic);
            Assert.AreEqual(EntityClassKeys.Patient, p.ClassConceptKey);
            Assert.AreEqual(DeterminerKeys.Specific, p.DeterminerConceptKey);
            Assert.AreEqual(StatusKeys.Active, p.StatusConceptKey);
            //Assert.AreEqual(aa.Key, afterInsert.Identifiers[0].AuthorityKey);
            var    jsonSerializer = new JsonViewModelSerializer();
            String json           = jsonSerializer.Serialize(afterInsert);

            Assert.IsNotNull(json);
        }
        public void TestSerializeActWithDefinition()
        {
            var act = new Act
            {
                ClassConceptKey = ActClassKeys.Encounter,
                CreationTime    = DateTimeOffset.Now,
                Key             = Guid.NewGuid(),
                MoodConceptKey  = ActMoodKeys.Eventoccurrence,
                Relationships   = new List <ActRelationship>
                {
                    new ActRelationship
                    {
                        RelationshipType = new Concept
                        {
                            Key      = ActRelationshipTypeKeys.HasSubject,
                            Mnemonic = "HasSubject"
                        },
                        TargetAct = new Act
                        {
                            Participations = new List <ActParticipation>
                            {
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.RecordTarget,
                                        Mnemonic = "RecordTarget"
                                    },
                                    PlayerEntity = this.m_patientUnderTest
                                },
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.Location,
                                        Mnemonic = "Location"
                                    },
                                    PlayerEntity = new Place
                                    {
                                        Key = Guid.Parse("AE2795E7-C40A-41CF-B77D-855EE2C3BF47")
                                    }
                                }
                            }
                        }
                    },
                    new ActRelationship
                    {
                        RelationshipType = new Concept
                        {
                            Key      = ActRelationshipTypeKeys.HasComponent,
                            Mnemonic = "HasComponent"
                        },
                        TargetAct = new Act
                        {
                            Participations = new List <ActParticipation>
                            {
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.RecordTarget,
                                        Mnemonic = "RecordTarget"
                                    },
                                    PlayerEntity = this.m_patientUnderTest
                                },
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.Location,
                                        Mnemonic = "Location"
                                    },
                                    PlayerEntity = new Place
                                    {
                                        Key = Guid.Parse("AE2795E7-C40A-41CF-B77D-855EE2C3BF47")
                                    }
                                }
                            }
                        }
                    }
                    ,
                    new ActRelationship
                    {
                        RelationshipType = new Concept
                        {
                            Key      = ActRelationshipTypeKeys.Fulfills,
                            Mnemonic = "Fulfills"
                        },
                        TargetAct = new Act
                        {
                            Key = Guid.NewGuid()
                        }
                    }
                }
            };

            ViewModelDescription vmd = ViewModelDescription.Load(typeof(ViewModelSerializerTest).Assembly.GetManifestResourceStream("SanteDB.Core.Applets.Test.MinActModel.xml"));

            var serializer = new JsonViewModelSerializer();

            serializer.ViewModel = vmd;
            var actual = serializer.Serialize(act);

            // Must always contain ID even if model doesn't specify it (for ref integrity)
            Assert.IsTrue(actual.Contains(act.Key.ToString()));
            // Must not have fulfills
            Assert.IsFalse(actual.Contains("\"Fulfills\""));

            Assert.IsTrue(actual.Contains(ActMoodKeys.Eventoccurrence.ToString()));
            Assert.IsTrue(actual.Contains(ActRelationshipTypeKeys.HasSubject.ToString()));
        }
예제 #20
0
        /// <summary>
        /// Serialize the reply
        /// </summary>
        public override void SerializeResponse(RestResponseMessage response, object[] parameters, object result)
        {
            try
            {
                // Outbound control
                var    httpRequest = RestOperationContext.Current.IncomingRequest;
                string accepts     = httpRequest.Headers["Accept"]?.ToLower(),
                       contentType = httpRequest.Headers["Content-Type"]?.ToLower();

                // The request was in JSON or the accept is JSON
                if (result is Stream) // TODO: This is messy, clean it up
                {
                    contentType   = "application/octet-stream";
                    response.Body = result as Stream;
                }
                else if (accepts?.StartsWith("application/json+sdb-viewmodel") == true &&
                         typeof(IdentifiedData).IsAssignableFrom(result?.GetType()))
                {
                    var viewModel = httpRequest.Headers["X-SanteDB-ViewModel"] ?? httpRequest.QueryString["_viewModel"];

                    // Create the view model serializer
                    using (AuthenticationContextExtensions.TryEnterDeviceContext())
                    {
                        var viewModelSerializer = new JsonViewModelSerializer();
                        viewModelSerializer.LoadSerializerAssembly(typeof(ActExtensionViewModelSerializer).Assembly);

                        if (!String.IsNullOrEmpty(viewModel))
                        {
                            var viewModelDescription = ApplicationContext.Current.GetService <IAppletManagerService>()?.Applets.GetViewModelDescription(viewModel);
                            viewModelSerializer.ViewModel = viewModelDescription;
                        }
                        else
                        {
                            viewModelSerializer.ViewModel = m_defaultViewModel;
                        }

                        using (var tms = new MemoryStream())
                            using (StreamWriter sw = new StreamWriter(tms, Encoding.UTF8))
                                using (JsonWriter jsw = new JsonTextWriter(sw))
                                {
                                    viewModelSerializer.Serialize(jsw, result as IdentifiedData);
                                    jsw.Flush();
                                    sw.Flush();
                                    response.Body = new MemoryStream(tms.ToArray());
                                }
                    }
                    contentType = "application/json+sdb-viewModel";
                }
                // The request was in XML and/or the accept is JSON
                else if ((accepts?.StartsWith("application/xml") == true ||
                          contentType?.StartsWith("application/xml") == true) &&
                         result?.GetType().GetCustomAttribute <XmlTypeAttribute>() != null)
                {
                    XmlSerializer xsz = XmlModelSerializerFactory.Current.CreateSerializer(result.GetType());
                    MemoryStream  ms  = new MemoryStream();
                    xsz.Serialize(ms, result);
                    contentType = "application/xml";
                    ms.Seek(0, SeekOrigin.Begin);
                    response.Body = ms;
                }
                else if (result is XmlSchema)
                {
                    MemoryStream ms = new MemoryStream();
                    (result as XmlSchema).Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    contentType   = "text/xml";
                    response.Body = ms;
                }
                else if (result != null)
                {
                    // Prepare the serializer
                    JsonSerializer jsz = new JsonSerializer();
                    jsz.Converters.Add(new StringEnumConverter());

                    // Write json data
                    using (MemoryStream ms = new MemoryStream())
                        using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                            using (JsonWriter jsw = new JsonTextWriter(sw))
                            {
                                jsz.DateFormatHandling    = DateFormatHandling.IsoDateFormat;
                                jsz.NullValueHandling     = NullValueHandling.Ignore;
                                jsz.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                                jsz.TypeNameHandling      = TypeNameHandling.Auto;
                                jsz.Converters.Add(new StringEnumConverter());
                                jsz.Serialize(jsw, result);
                                jsw.Flush();
                                sw.Flush();
                                response.Body = new MemoryStream(ms.ToArray());
                            }

                    // Prepare reply for the WCF pipeline
                    contentType = "application/json";
                }
                else if (response.StatusCode == 0)
                {
                    response.StatusCode = 204; // no content
                }
                RestOperationContext.Current.OutgoingResponse.ContentType = RestOperationContext.Current.OutgoingResponse.ContentType ?? contentType;
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceError("Error Serializing Dispatch Reply: {0}", e.ToString());
                new AgsErrorHandlerServiceBehavior().ProvideFault(e, response);
            }
        }
예제 #21
0
        /// <summary>
        /// Deserialize the request
        /// </summary>
        public override void DeserializeRequest(EndpointOperation operation, RestRequestMessage request, object[] parameters)
        {
            try
            {
#if DEBUG
                this.m_traceSource.TraceInfo("Received request from: {0}", RestOperationContext.Current.IncomingRequest.RemoteEndPoint);
#endif

                var    httpRequest = RestOperationContext.Current.IncomingRequest;
                string contentType = httpRequest.Headers["Content-Type"]?.ToLowerInvariant();

                for (int pNumber = 0; pNumber < parameters.Length; pNumber++)
                {
                    var parm = operation.Description.InvokeMethod.GetParameters()[pNumber];

                    // Simple parameter
                    if (parameters[pNumber] != null)
                    {
                        continue; // dispatcher already populated
                    }
                    // Use XML Serializer
                    else if (contentType?.StartsWith("application/xml") == true)
                    {
                        using (XmlReader bodyReader = XmlReader.Create(request.Body))
                        {
                            while (bodyReader.NodeType != XmlNodeType.Element)
                            {
                                bodyReader.Read();
                            }

                            Type eType = s_knownTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlRootAttribute>()?.ElementName == bodyReader.LocalName &&
                                                                     o.GetCustomAttribute <XmlRootAttribute>()?.Namespace == bodyReader.NamespaceURI);
                            var serializer = XmlModelSerializerFactory.Current.CreateSerializer(eType);
                            parameters[pNumber] = serializer.Deserialize(request.Body);
                        }
                    }
                    else if (contentType?.StartsWith("application/json+sdb-viewmodel") == true)
                    {
                        var viewModel = httpRequest.Headers["X-SanteDB-ViewModel"] ?? httpRequest.QueryString["_viewModel"];

                        // Create the view model serializer
                        var viewModelSerializer = new JsonViewModelSerializer();
                        viewModelSerializer.LoadSerializerAssembly(typeof(ActExtensionViewModelSerializer).Assembly);

                        if (!String.IsNullOrEmpty(viewModel))
                        {
                            var viewModelDescription = ApplicationContext.Current.GetService <IAppletManagerService>()?.Applets.GetViewModelDescription(viewModel);
                            viewModelSerializer.ViewModel = viewModelDescription;
                        }
                        else
                        {
                            viewModelSerializer.ViewModel = m_defaultViewModel;
                        }

                        using (var sr = new StreamReader(request.Body))
                            parameters[pNumber] = viewModelSerializer.DeSerialize(sr, parm.ParameterType);
                    }
                    else if (contentType?.StartsWith("application/json") == true)
                    {
                        using (var sr = new StreamReader(request.Body))
                            using (var jsr = new JsonTextReader(sr))
                            {
                                JsonSerializer jsz = new JsonSerializer()
                                {
                                    SerializationBinder            = new ModelSerializationBinder(parm.ParameterType),
                                    TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
                                    TypeNameHandling = TypeNameHandling.All
                                };
                                jsz.Converters.Add(new StringEnumConverter());

                                // Can the binder resolve the type from the message?
                                parameters[pNumber] = jsz.Deserialize(jsr, parm.ParameterType);
                            }
                    }
                    else if (contentType == "application/octet-stream")
                    {
                        parameters[pNumber] = request.Body;
                    }
                    else if (contentType == "application/x-www-form-urlencoded")
                    {
                        NameValueCollection nvc = new NameValueCollection();
                        using (var sr = new StreamReader(request.Body))
                        {
                            var ptext = sr.ReadToEnd();
                            var parms = ptext.Split('&');
                            foreach (var p in parms)
                            {
                                var parmData = p.Split('=');
                                nvc.Add(WebUtility.UrlDecode(parmData[0]), WebUtility.UrlDecode(parmData[1]));
                            }
                        }
                        parameters[pNumber] = nvc;
                    }
                    else if (contentType != null)// TODO: Binaries
                    {
                        throw new InvalidOperationException("Invalid request format");
                    }
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceError("Error de-serializing dispatch request: {0}", e.ToString());
                throw;
            }
        }
예제 #22
0
        public void TestSerializeActWithDeepNestDefinition()
        {
            var act = new Act
            {
                ClassConcept = new Concept
                {
                    Key = ActClassKeys.Encounter
                },
                CreationTime = DateTimeOffset.Now,
                Key          = Guid.NewGuid(),
                MoodConcept  = new Concept
                {
                    Key = ActMoodKeys.Eventoccurrence
                },
                Relationships = new List <ActRelationship>
                {
                    new ActRelationship
                    {
                        RelationshipType = new Concept
                        {
                            Key      = ActRelationshipTypeKeys.HasSubject,
                            Mnemonic = "HasSubject"
                        },
                        TargetAct = new Act
                        {
                            Participations = new List <ActParticipation>
                            {
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.RecordTarget,
                                        Mnemonic = "RecordTarget"
                                    },
                                    PlayerEntity = this.m_patientUnderTest
                                },
                                new ActParticipation
                                {
                                    ParticipationRole = new Concept
                                    {
                                        Key      = ActParticipationKey.Location,
                                        Mnemonic = "Location"
                                    },
                                    PlayerEntity = new Place
                                    {
                                        Key = Guid.Parse("AE2795E7-C40A-41CF-B77D-855EE2C3BF47")
                                    }
                                }
                            }
                        }
                    }
                }
            };

            this.m_patientUnderTest.Names[0].Component[0].ComponentType = new Concept()
            {
                Key      = NameComponentKeys.Family,
                Mnemonic = "Family"
            };
            ViewModelDescription vmd = ViewModelDescription.Load(typeof(ViewModelSerializerTest).Assembly.GetManifestResourceStream("OpenIZ.Core.Applets.Test.DeepActModel.xml"));
            var serializer           = new JsonViewModelSerializer();

            serializer.ViewModel = vmd;
            var actual = serializer.Serialize(act);

            Assert.IsTrue(actual.Contains(ActMoodKeys.Eventoccurrence.ToString()));
            Assert.IsTrue(actual.Contains(ActRelationshipTypeKeys.HasSubject.ToString()));
        }
예제 #23
0
        public void TestPersistPatient()
        {
            Patient p = new Patient()
            {
                StatusConceptKey = StatusKeys.Active,
                Names            = new List <EntityName>()
                {
                    new EntityName(NameUseKeys.OfficialRecord, "Johnson", "William", "P.", "Bear")
                },
                Addresses = new List <EntityAddress>()
                {
                    new EntityAddress(AddressUseKeys.HomeAddress, "123 Main Street West", "Hamilton", "ON", "CA", "L8K5N2")
                },
                Identifiers = new List <EntityIdentifier>()
                {
                    new EntityIdentifier(new AssigningAuthority()
                    {
                        Name = "OHIPCARD12", DomainName = "OHIPCARD12", Oid = "1.2.3.4.5.6"
                    }, "12343120423")
                },
                Telecoms = new List <EntityTelecomAddress>()
                {
                    new EntityTelecomAddress(AddressUseKeys.WorkPlace, "mailto:[email protected]")
                },
                Tags = new List <EntityTag>()
                {
                    new EntityTag("hasBirthCertificate", "true")
                },
                Notes = new List <EntityNote>()
                {
                    new EntityNote(Guid.Empty, "William is a test patient")
                    {
                        Author = new Person()
                    }
                },
                Extensions = new List <EntityExtension>()
                {
                    new EntityExtension()
                    {
                        ExtensionType = new ExtensionType()
                        {
                            Name             = "http://openiz.org/oiz/birthcertificate",
                            ExtensionHandler = typeof(EntityPersistenceServiceTest)
                        },
                        ExtensionValueXml = new byte[] { 1 }
                    }
                },
                GenderConceptKey      = Guid.Parse("f4e3a6bb-612e-46b2-9f77-ff844d971198"),
                DateOfBirth           = new DateTime(1984, 03, 22),
                MultipleBirthOrder    = 2,
                DeceasedDate          = new DateTime(2016, 05, 02),
                DeceasedDatePrecision = DatePrecision.Day,
                DateOfBirthPrecision  = DatePrecision.Day
            };

            Person mother = new Person()
            {
                StatusConceptKey = StatusKeys.Active,
                Names            = new List <EntityName>()
                {
                    new EntityName(NameUseKeys.Legal, "Johnson", "Martha")
                }
            };

            // Associate: PARENT > CHILD
            p.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Mother, mother));

            var afterInsert = base.DoTestInsert(p, s_authorization);

            Assert.AreEqual(DatePrecision.Day, afterInsert.DateOfBirthPrecision);
            Assert.AreEqual(DatePrecision.Day, afterInsert.DeceasedDatePrecision);
            Assert.AreEqual(new DateTime(1984, 03, 22), afterInsert.DateOfBirth);
            Assert.AreEqual(new DateTime(2016, 05, 02), afterInsert.DeceasedDate);
            Assert.AreEqual("Male", afterInsert.GenderConcept.Mnemonic);
            Assert.AreEqual(2, afterInsert.MultipleBirthOrder);
            Assert.AreEqual(1, p.Names.Count);
            Assert.AreEqual(1, p.Addresses.Count);
            Assert.AreEqual(1, p.Identifiers.Count);
            Assert.AreEqual(1, p.Telecoms.Count);
            Assert.AreEqual(1, p.Tags.Count);
            Assert.AreEqual(1, p.Notes.Count);
            Assert.AreEqual(EntityClassKeys.Patient, p.ClassConceptKey);
            Assert.AreEqual(DeterminerKeys.Specific, p.DeterminerConceptKey);
            Assert.AreEqual(StatusKeys.Active, p.StatusConceptKey);

            var    jsonSerializer = new JsonViewModelSerializer();
            String json           = jsonSerializer.Serialize(afterInsert);

            Assert.IsNotNull(json);
        }