public static bool TryValidate(ResourceEntry entry, ICollection<ValidationResult> validationResults = null)
        {
            if (entry == null) throw new ArgumentNullException("entry");

            var results = validationResults ?? new List<ValidationResult>();
            return Validator.TryValidateObject(entry, ValidationContextFactory.Create(entry, null), results, true);
        }
Beispiel #2
0
        public void TestSigning()
        {
            Bundle b = new Bundle();

            b.Title = "Updates to resource 233";
            b.Id = new Uri("urn:uuid:0d0dcca9-23b9-4149-8619-65002224c3");
            b.LastUpdated = new DateTimeOffset(2012, 11, 2, 14, 17, 21, TimeSpan.Zero);
            b.AuthorName = "Ewout Kramer";

            ResourceEntry<Patient> p = new ResourceEntry<Patient>();
            p.Id = new ResourceIdentity("http://test.com/fhir/Patient/233");
            p.Resource = new Patient();
            p.Resource.Name = new List<HumanName> { HumanName.ForFamily("Kramer").WithGiven("Ewout") };
            b.Entries.Add(p);

            var myAssembly = typeof(TestXmlSignature).Assembly;
            var stream = myAssembly.GetManifestResourceStream("Spark.Tests.spark.pfx");

            var data = new byte[stream.Length];
            stream.Read(data,0,(int)stream.Length);
            var certificate = new X509Certificate2(data);

            var bundleData = FhirSerializer.SerializeBundleToXmlBytes(b);
            var bundleXml = Encoding.UTF8.GetString(bundleData);

            var bundleSigned = XmlSignatureHelper.Sign(bundleXml, certificate);

            Assert.IsTrue(XmlSignatureHelper.IsSigned(bundleSigned));
            Assert.IsTrue(XmlSignatureHelper.VerifySignature(bundleSigned));

            var changedBundle = bundleSigned.Replace("<name>Ewout", "<name>Ewald");
            Assert.AreEqual(bundleSigned.Length, changedBundle.Length);

            Assert.IsFalse(XmlSignatureHelper.VerifySignature(changedBundle));
        }
Beispiel #3
0
        private ResourceEntry internalCreate(ResourceEntry internalEntry)
        {
            ResourceEntry entry = (ResourceEntry)store.AddEntry(internalEntry);
            _index.Process(internalEntry);

            return entry;
        }
Beispiel #4
0
 public void Put(ResourceEntry entry)
 {
     lock (transaction)
     {
         indexer.Put(entry);
     }
 }
Beispiel #5
0
        public void TestTagsOnCreateAndRead()
        {
            var tags = new List<Tag>() { new Tag(NUTAG, Tag.FHIRTAGNS, "readTagTest") };
            
            HttpTests.AssertSuccess(client, () => latest = client.Create<Patient>(DemoData.GetDemoPatient(),tags));

            if(latest.Tags == null)
                TestResult.Fail("create did not return any tags");

            var nutags = latest.Tags.FindByTerm(NUTAG, Tag.FHIRTAGNS);
            if (nutags.Count() != 1 || nutags.First().Label != "readTagTest")
                TestResult.Fail("create did not return specified tag");

            var read = client.Fetch<Patient>(latest.Id);
            if (read.Tags == null)
                TestResult.Fail("read did not return any tags");
            nutags = latest.Tags.FindByTerm(NUTAG, Tag.FHIRTAGNS);
            if (nutags.Count() != 1 || nutags.First().Label != "readTagTest")
                TestResult.Fail("read did not return specified tag");

            var vread = client.Fetch<Patient>(latest.SelfLink);
            if (vread.Tags == null)
                TestResult.Fail("vread did not return any tags");
            nutags = latest.Tags.FindByTerm(NUTAG, Tag.FHIRTAGNS);
            if (nutags.Count() != 1 || nutags.First().Label != "readTagTest")
                TestResult.Fail("vread did not return specified tag");

            original = latest;
        }
Beispiel #6
0
        public void UpdateTagsOnUpdate()
        {
            if (original == null) TestResult.Skipped();

            // Update one tag, add another
            var tags = new List<Tag>() { 
                new Tag(NUTAG, Tag.FHIRTAGNS, "readTagTest2"), 
                new Tag(OTHERTAG, Tag.FHIRTAGNS, "dummy") };

            HttpTests.AssertSuccess(client, () => latest = client.Fetch<Patient>(original.Id));

            latest.Tags = tags;

            HttpTests.AssertSuccess(client, () => client.Update<Patient>(latest));

            var read = client.Fetch<Patient>(latest.Id);

            if (read.Tags == null)
                TestResult.Fail("fetch after update did not return any tags");

            if (read.Tags.Count() != 2)
                TestResult.Fail(String.Format("Wrong number of tags after update: {0}, expected 2", read.Tags.Count()));
            var nutags = read.Tags.FindByTerm(NUTAG,Tag.FHIRTAGNS);
            if (nutags.Count() != 1 || nutags.First().Label != "readTagTest2")
                TestResult.Fail("update did not replace value in tag");
            var othertags = read.Tags.FindByTerm(OTHERTAG,Tag.FHIRTAGNS);
            if(othertags.Count() != 1 || othertags.First().Label != "dummy")
                TestResult.Fail("update failed to add new tag");

            latest = read;
        }
        public void TestSigning()
        {
            Bundle b = new Bundle();

            b.Title = "Updates to resource 233";
            b.Id = new Uri("urn:uuid:0d0dcca9-23b9-4149-8619-65002224c3");
            b.LastUpdated = new DateTimeOffset(2012, 11, 2, 14, 17, 21, TimeSpan.Zero);
            b.AuthorName = "Ewout Kramer";

            ResourceEntry<Patient> p = new ResourceEntry<Patient>();
            p.Id = new ResourceIdentity("http://test.com/fhir/Patient/233");
            p.Resource = new Patient();
            p.Resource.Name = new List<HumanName> { HumanName.ForFamily("Kramer").WithGiven("Ewout") };
            b.Entries.Add(p);

            var certificate = getCertificate();

            var bundleData = FhirSerializer.SerializeBundleToXmlBytes(b);
            var bundleXml = Encoding.UTF8.GetString(bundleData);
            var bundleSigned = XmlSignatureHelper.Sign(bundleXml, certificate);
            _signedXml = bundleSigned;

            using (var response = postBundle(bundleSigned))
            {
                if (response.StatusCode != HttpStatusCode.OK) TestResult.Fail("Server refused POSTing signed document at /");
            }
        }
 public static HttpResponseMessage ResourceResponse(this HttpRequestMessage request, ResourceEntry entry)
 {
     request.SaveEntry(entry);
     HttpResponseMessage msg = request.CreateResponse<ResourceEntry>(entry);
     msg.Headers.SetFhirTags(entry.Tags);
     return msg;
 }
Beispiel #9
0
 public void Put(ResourceEntry entry)
 {
     if (entry is ResourceEntry)
     {
         Put(entry, 0, entry.Resource);
     }
 }
Beispiel #10
0
        public HttpResponseMessage Create(string type, ResourceEntry entry)
        {
            entry.Tags = Request.GetFhirTags(); // todo: move to model binder?

            ResourceEntry newentry = service.Create(entry, type);
            return Request.StatusResponse(newentry, HttpStatusCode.Created);
        }
        public void AddPatient()
        {
            Patient patient = Utils.NewPatient("Bach", "Johan", "Sebastian");
            entry = client.Create<Patient>(patient, null, true);

            Bundle bundle = client.History(entry);
            TestResult.Assert((bundle.Entries.Count == 1), "History of patient is not valid");
        }
 private static void compareData(byte[] data, ResourceEntry<Binary> received)
 {
     if (data.Length != received.Resource.Content.Length)
         TestResult.Fail("Binary data returned has a different size");
     for (int pos = 0; pos < data.Length; pos++)
         if (data[pos] != received.Resource.Content[pos])
             TestResult.Fail("Binary data returned differs from original");
 }
Beispiel #13
0
 private void Put(ResourceEntry entry, int level, IEnumerable<Resource> resources)
 {
     if (resources == null) return;
     foreach (var resource in resources)
     {
         Put(entry, level, resource);
     }
 }
 public static HttpResponseMessage StatusResponse(this HttpRequestMessage request, ResourceEntry entry, HttpStatusCode code)
 {
     request.SaveEntry(entry);
     HttpResponseMessage msg = request.CreateResponse(code);
     msg.Headers.SetFhirTags(entry.Tags); // todo: move to model binder
     msg.Headers.Location = entry.SelfLink;
     return msg;
 }
        public void Updating()
        {
            // Birthday of Bach on Gregorian calendar
            entry.Resource.BirthDate = "1685-03-21";
            entry = client.Update<Patient>(entry, true);

            Bundle bundle = client.History(entry);
            TestResult.Assert((bundle.Entries.Count == 2), "History of patient is not valid");
        }
Beispiel #16
0
        public void TextTagHandling()
        {
            var r = new ResourceEntry<Patient>();
            var text = "<b>Bold! Eeuww  some /\\ url unfriendly stuff !@#$%^& //</b>";

            r.SetTextTag(text);

            var text2 = r.GetTextTag();

            Assert.AreEqual(text, text2);
        }
        public void TextTagHandling()
        {
            var r    = new ResourceEntry <Patient>();
            var text = "<b>Bold! Eeuww  some /\\ url unfriendly stuff !@#$%^& //</b>";

            r.SetTextTag(text);

            var text2 = r.GetTextTag();

            Assert.AreEqual(text, text2);
        }
Beispiel #18
0
 public static void ValidateEntry(ResourceEntry entry)
 {
     try
     {
         ModelValidator.Validate(entry);
     }
     catch (Exception e)
     {
         throw new SparkException(HttpStatusCode.BadRequest, "Validation failed", e);
     }
 }
Beispiel #19
0
        public void ValidateUpdateResource()
        {
            Patient patient = DemoData.GetDemoPatient();
            ResourceEntry <Patient> result = client.Create <Patient>(patient);

            OperationOutcome oo;

            if (!client.TryValidateUpdate(result, out oo))
            {
                TestResult.Fail("Validation incorrectly reported failure.");
            }
        }
        private void PostProcessBone(VoidPtr mdlAddress, MDL0EntryNode node, ResourceGroup *group, ref int index, StringTable stringTable)
        {
            VoidPtr dataAddress = (VoidPtr)group + (&group->_first)[index]._dataOffset;

            ResourceEntry.Build(group, index++, dataAddress, (BRESString *)stringTable[node.Name]);
            node.PostProcess(mdlAddress, dataAddress, stringTable);

            foreach (MDL0EntryNode n in node.Children)
            {
                PostProcessBone(mdlAddress, n, group, ref index, stringTable);
            }
        }
Beispiel #21
0
        public ResourceEntry WriteAudioSectorEntry(ResourceEntry entry, XPathNodeIterator nodes, string sdsFolder, XmlNode descNode)
        {
            string file;

            nodes.Current.MoveToNext();
            file       = nodes.Current.Value;
            entry.Data = File.ReadAllBytes(sdsFolder + "/" + file);
            nodes.Current.MoveToNext();
            entry.Version      = Convert.ToUInt16(nodes.Current.Value);
            descNode.InnerText = file;
            return(entry);
        }
Beispiel #22
0
        //[SprinklerTest("TR10", "Failing data")]
        public void FailingData()
        {
            Patient    p    = new Patient();
            Identifier item = new Identifier();

            item.Label   = "hl7v2";
            item.Value   = "PID-55101";
            p.Identifier = new List <Identifier>();
            p.Identifier.Add(item);
            p.BirthDate = "1974-02-20";
            ResourceEntry <Patient> r = client.Create <Patient>(p);
        }
Beispiel #23
0
        /// <summary>
        /// Update (or create) a resource at a given endpoint
        /// </summary>
        /// <param name="entry">A ResourceEntry containing the resource to update</param>
        /// <param name="versionAware">Whether or not version aware update is used.</param>
        /// <typeparam name="TResource">The type of resource that is being updated</typeparam>
        /// <returns>The resource as updated on the server. Throws an exception when the update failed,
        /// in particular may throw an exception when the server returns a 409 when a conflict is detected
        /// while using version-aware updates or 412 if the server requires version-aware updates.</returns>
        public ResourceEntry <TResource> Update <TResource>(ResourceEntry <TResource> entry, bool versionAware = false)
            where TResource : Resource, new()
        {
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }
            if (entry.Resource == null)
            {
                throw new ArgumentException("Entry does not contain a Resource to update", "entry");
            }
            if (entry.Id == null)
            {
                throw new ArgumentException("Entry needs a non-null entry.id to send the update to", "entry");
            }
            if (versionAware && entry.SelfLink == null)
            {
                throw new ArgumentException("When requesting version-aware updates, Entry.SelfLink may not be null.", "entry");
            }

            string contentType = null;

            byte[] data = null;

            if (entry.Resource is Binary)
            {
                var bin = entry.Resource as Binary;
                data        = bin.Content;
                contentType = bin.ContentType;
            }
            else
            {
                data = PreferredFormat == ContentType.ResourceFormat.Xml ?
                       FhirSerializer.SerializeResourceToXmlBytes(entry.Resource) :
                       FhirSerializer.SerializeResourceToJsonBytes(entry.Resource);
                contentType = ContentType.BuildContentType(PreferredFormat, false);
            }

            var req = createRequest(entry.Id, false);

            req.Method      = "PUT";
            req.ContentType = contentType;
            prepareRequest(req, data, entry.Tags);

            // If a version id is given, post the data to a version-specific url
            if (versionAware)
            {
                req.Headers[HttpRequestHeader.ContentLocation] = entry.SelfLink.ToString();
            }

            return(doRequest(req, new HttpStatusCode[] { HttpStatusCode.Created, HttpStatusCode.OK },
                             () => resourceEntryFromResponse <TResource>()));
        }
Beispiel #24
0
        public Bundle Mailbox(Bundle bundle, Binary body)
        {
            if (bundle == null || body == null)
            {
                throw new SparkException("Mailbox requires a Bundle body payload");
            }
            // For the connectathon, this *must* be a document bundle
            if (bundle.GetBundleType() != BundleType.Document)
            {
                throw new SparkException("Mailbox endpoint currently only accepts Document feeds");
            }

            Bundle result = new Bundle("Transaction result from posting of Document " + bundle.Id, DateTimeOffset.Now);

            // Build a binary with the original body content (=the unparsed Document)
            var binaryEntry = new ResourceEntry <Binary>(new Uri("cid:" + Guid.NewGuid()), DateTimeOffset.Now, body);

            binaryEntry.SelfLink = new Uri("cid:" + Guid.NewGuid());

            // Build a new DocumentReference based on the 1 composition in the bundle, referring to the binary
            var compositions = bundle.Entries.OfType <ResourceEntry <Composition> >();

            if (compositions.Count() != 1)
            {
                throw new SparkException("Document feed should contain exactly 1 Composition resource");
            }
            var composition = compositions.First().Resource;
            var reference   = ConnectathonDocumentScenario.DocumentToDocumentReference(composition, bundle, body, binaryEntry.SelfLink);

            // Start by copying the original entries to the transaction, minus the Composition
            List <BundleEntry> entriesToInclude = new List <BundleEntry>();

            //TODO: Only include stuff referenced by DocumentReference
            //if(reference.Subject != null) entriesToInclude.AddRange(bundle.Entries.ById(new Uri(reference.Subject.Reference)));
            //if (reference.Author != null) entriesToInclude.AddRange(
            //         reference.Author.Select(auth => bundle.Entries.ById(auth.Id)).Where(be => be != null));
            //reference.Subject = composition.Subject;
            //reference.Author = new List<ResourceReference>(composition.Author);
            //reference.Custodian = composition.Custodian;

            foreach (var entry in bundle.Entries.Where(be => !(be is ResourceEntry <Composition>)))
            {
                result.Entries.Add(entry);
            }

            // Now add the newly constructed DocumentReference and the Binary
            result.Entries.Add(new ResourceEntry <DocumentReference>(new Uri("cid:" + Guid.NewGuid()), DateTimeOffset.Now, reference));
            result.Entries.Add(binaryEntry);

            // Process the constructed bundle as a Transaction and return the result
            return(Transaction(result));
        }
Beispiel #25
0
        public void TestStoreBinaryEntry()
        {
            byte[] data = UTF8Encoding.UTF8.GetBytes("Hello world!");

            var e = new ResourceEntry <Binary>();

            e.AuthorName     = "Ewout";
            e.Id             = new Uri("binary/@3141", UriKind.Relative);
            e.Links.SelfLink = new Uri("binary/@3141/history/@1", UriKind.Relative);
            e.Resource       = new Binary()
            {
                Content = data, ContentType = "text/plain"
            };

            // Test store
            var result = (ResourceEntry <Binary>)_store.AddEntry(e);

            Assert.IsNotNull(result.Resource);
            CollectionAssert.AreEqual(data, result.Resource.Content);
            Assert.AreEqual("text/plain", result.Resource.ContentType);

            // Test retrieve
            ResourceEntry <Binary> result2 = (ResourceEntry <Binary>)_store.FindEntryById(e.Id);

            Assert.IsNotNull(result2);
            CollectionAssert.AreEqual(e.Resource.Content, result2.Resource.Content);
            Assert.AreEqual(e.Resource.ContentType, result2.Resource.ContentType);

            // Test update
            byte[] data2 = UTF8Encoding.UTF8.GetBytes("Hello world!?");
            e.Resource = new Binary()
            {
                Content = data2, ContentType = "text/plain"
            };
            e.SelfLink = new Uri("binary/@3141/history/@2", UriKind.Relative);
            ResourceEntry <Binary> result3 = (ResourceEntry <Binary>)_store.AddEntry(e);

            Assert.IsNotNull(result3);
            Assert.AreEqual(e.Resource.ContentType, result3.Resource.ContentType);
            CollectionAssert.AreEqual(e.Resource.Content, result3.Resource.Content);

            // Test fetch latest
            ResourceEntry <Binary> result4 = (ResourceEntry <Binary>)_store.FindEntryById(e.Id);

            Assert.AreEqual(result4.Id, result3.Id);

            var allVersions = _store.ListVersionsById(e.Id);

            Assert.AreEqual(2, allVersions.Count());
            Assert.AreEqual(allVersions.First().Id, e.Id);
            Assert.AreEqual(allVersions.Skip(1).First().Id, result.Id);
        }
			/// <summary>
			/// Applied after Hover runs.
			/// </summary>
			/// <param name="__instance">The current resource entry.</param>
			/// <param name="is_hovering">true if the user is hovering, or false otherwise</param>
			/// <param name="___HighlightColor">The highlight color from the instance.</param>
			internal static void Postfix(ResourceEntry __instance, bool is_hovering,
					Color ___HighlightColor) {
				var info = __instance.gameObject.GetComponent<CritterResourceInfo>();
				if (info != null) {
					var hlc = ___HighlightColor;
					CritterType type = info.CritterType;
					Tag species = __instance.Resource;
					CritterInventoryUtils.IterateCreatures((creature) => {
						if (creature.PrefabID() == species && type.Matches(creature))
							PUtil.HighlightEntity(creature, is_hovering ? hlc : Color.black);
					});
				}
			}
Beispiel #27
0
        public void Enqueue(ResourceEntry entry)
        {
            //if (id == null) throw new ArgumentNullException("id");
            //if (!id.IsAbsoluteUri) throw new ArgumentException("Uri for new resource must be absolute");

            var location = new ResourceIdentity(entry.Id);
            var title    = String.Format("{0} resource with id {1}", location.Collection, location.Id);

            entry.Title = entry.Title ?? title;
            //var newEntry = BundleEntryFactory.CreateFromResource(entry.Resource, id, DateTimeOffset.Now, title);
            //newEntry.Tags = entry.Tags;
            queue.Enqueue(entry);
        }
Beispiel #28
0
        public void Add(Resource resource, int count)
        {
            ResourceEntry entry = Find(resource);

            if (entry != null)
            {
                entry.count += count;
            }
            else
            {
                resources.Add(new ResourceEntry(resource, count));
            }
        }
Beispiel #29
0
    /// <summary>
    /// Initialize the resources.
    /// </summary>

    void InitResources()
    {
        if (mResources.Count == 0)
        {
            for (int i = 0; i < TownResources.Instance.list.Count; ++i)
            {
                ResourceEntry entry = new ResourceEntry();
                entry.production = GetStartingResource(i);
                entry.warehouse  = 0;
                mResources.Add(entry);
            }
        }
    }
        public Task <ResourceEntry> GetArchiveResource(string name, ConfigurationIdentity identity)
        {
            string path = Path.Combine(GetArchiveResourceSetFolder(identity).FullName, name);

            var result = new ResourceEntry()
            {
                Name     = name,
                Content  = File.OpenRead(path),
                HasEntry = File.Exists(path)
            };

            return(Task.FromResult(result));
        }
Beispiel #31
0
        public static void RGB(string name, ResourceEntry re)
        {
            var entry = re as ResourceEntry_Image;

            entry.name = name;
            var bytes = BytesForFile(name);

            entry.Image = SGIReader.Parse(bytes);
            if (entry.Image == null)
            {
                entry.Image = new Image <Color32>();
            }
        }
Beispiel #32
0
        public bool IsJunkEntry(ResourceEntry rEntry)
        {
            if (!SkipTrashEntries)
            {
                return(false);
            }

            if ((rEntry.Flags & 0x2000) == 0x2000) //Empty folders, probably used for debug
            {
                return(true);
            }
            return(false);
        }
Beispiel #33
0
        public void QueueNewResourceEntry(Uri id, ResourceEntry entry)
        {
            if (id == null) throw new ArgumentNullException("id");
            if (!id.IsAbsoluteUri) throw new ArgumentException("Uri for new resource must be absolute");

            var location = new ResourceIdentity(id);
            var title = String.Format("{0} resource with id {1}", location.Collection, location.Id);
            

            var newEntry = BundleEntryFactory.CreateFromResource(entry.Resource, id, DateTimeOffset.Now, title);
            newEntry.Tags = entry.Tags;
            queue.Add(newEntry);
        }
Beispiel #34
0
        public void TestResourceImages()
        {
            using DataTarget dt = TestTargets.AppDomains.LoadFullDump();
            ClrInfo clr = dt.ClrVersions.Single();

            using PEImage image = ((PEModuleInfo)clr.ModuleInfo).GetPEImage();
            ResourceEntry entry = image.Resources;

            bool found = false;

            WalkEntry(entry, ref found);
            Assert.True(found);
        }
Beispiel #35
0
        public void Validate(string collection, ResourceEntry entry)
        {
            RequestValidator.ValidateCollectionName(collection);
            if (entry == null)
            {
                throw new SparkException("Validate needs a Resource in the body payload");
            }

            entry.Title       = "Validation test entity";
            entry.LastUpdated = DateTime.Now;
            entry.Id          = ResourceIdentity.Build(Endpoint, collection, getNewId());
            RequestValidator.ValidateEntry(entry);
        }
Beispiel #36
0
        public ResourceEntry Upsert(ResourceEntry entry, string collection, string id)
        {
            Uri key = BuildKey(collection, id);

            if (store.Exists(key))
            {
                return(Update(entry, collection, id));
            }
            else
            {
                return(Create(entry, collection, id));
            }
        }
Beispiel #37
0
        public ResourceEntry WriteAnimationEntry(ResourceEntry entry, XPathNodeIterator nodes, string sdsFolder, XmlNode descNode)
        {
            //get data from xml:
            nodes.Current.MoveToNext();
            string file = nodes.Current.Value;

            nodes.Current.MoveToNext();
            entry.Version = Convert.ToUInt16(nodes.Current.Value);
            entry.Data    = File.ReadAllBytes(sdsFolder + "/" + file);
            //finish
            descNode.InnerText = file.Remove(file.Length - 4, 4);
            return(entry);
        }
Beispiel #38
0
        public void QueueNewResourceEntry(string collection, string id, ResourceEntry entry)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }
            if (id == null)
            {
                throw new ArgumentNullException("resource");
            }

            QueueNewResourceEntry(ResourceIdentity.Build(_endpoint, collection, id), entry);
        }
Beispiel #39
0
        //internal static ResourceEntry<Binary> CreateFromBinary(byte[] data, string mediaType, Uri id, DateTimeOffset updated, string title = null)
        //{
        //    var result = new ResourceEntry<Binary>();

        //    if (title == null)
        //        title = "Binary entry containing " + mediaType;

        //    initializeResourceEntry(result, id, updated, title);

        //    result.Content = new Binary() { Content = data, ContentType = mediaType };

        //    return result;
        //}

        private static void initializeResourceEntry(ResourceEntry member, Uri id, DateTimeOffset updated, string title)
        {
            member.Id = id;
            member.LastUpdated = updated;
            member.Published = DateTimeOffset.Now;      // Time copied into feed
            member.Title = title;

            var userIdentity = System.Threading.Thread.CurrentPrincipal.Identity;
            member.AuthorName = userIdentity != null && !String.IsNullOrEmpty(userIdentity.Name) ?
                                        userIdentity.Name : "(unauthenticated)";

            member.AuthorUri = null; //TODO: how to get a meaningful AuthorUri?
        }
        public ActionResult MedicalHistory(string ID)
        {
            SearchViewModel           m             = new SearchViewModel();
            List <ConditionViewModel> conditionList = new List <ConditionViewModel>();

            var client = new FhirClient("http://fhirtest.uhn.ca/baseDstu1");

            //search patients based on patientID clicked
            Bundle resultsPatients = client.Search <Patient>(new string[] { "_id=" + ID });


            //gets patient based on ID
            foreach (var entry in resultsPatients.Entries)
            {
                ResourceEntry <Patient> patient = (ResourceEntry <Patient>)entry;

                m = getPatientInfo(patient);
            }

            Bundle resultsConditions = client.Search <Condition>(new string[] { "subject=" + ID });

            foreach (var entry in resultsConditions.Entries)
            {
                ConditionViewModel        conditions = new ConditionViewModel();
                ResourceEntry <Condition> condition  = (ResourceEntry <Condition>)entry;
                if (condition.Resource.Code != null)
                {
                    conditions.ConditionName = condition.Resource.Code.Text;
                }
                else
                {
                    conditions.ConditionName = "Unknown";
                }

                if (condition.Resource.Onset != null)
                {
                    conditions.Date = (condition.Resource.Onset as Date).Value;
                }
                else
                {
                    conditions.Date = "Unknown";
                }
                m.ConditionsCount++;
                conditionList.Add(conditions);
            }

            m.Conditions = conditionList;

            patients.Add(m);
            return(View(patients));
        }
        public string DetermineName(ResourceEntry entry, string name)
        {
            bool bGotDebugName = false;

            // Make sure we use the debug name.
            if (!string.IsNullOrEmpty(DebugName))
            {
                name          = DebugName;
                bGotDebugName = true;
            }

            // We found the name already
            if (FNV64.Hash(name) == entry.FileHash)
            {
                name = ReplaceCurrentExtension(name);
                return(name);
            }

            // Our database tool has figured out this file name.
            // Return.
            // TODO: Consider an easier approach for this, maybe have a flag?
            if (!name.Contains("File_") && !bGotDebugName)
            {
                string extension = GetFullExtensionUtil(name);
                if (!TypeExtensionString.ContainsKey(extension))
                {
                    MessageBox.Show("Detected missing extension from DB. Please contract Greavesy with SDS name.", "Toolkit");
                }
                return(name);
            }

            if (!bGotDebugName)
            {
                string withoutExtension = Path.GetFileNameWithoutExtension(name);

                if (TypeExtensionMagic.ContainsKey(GenericType))
                {
                    string extension = TypeExtensionMagic[GenericType];
                    withoutExtension += extension;
                }
                else
                {
                    withoutExtension += ".genr";
                    MessageBox.Show("Detected an unknown GENR type. Please contract Greavesy with SDS name.", "Toolkit");
                }

                name = withoutExtension;
            }

            return(name);
        }
Beispiel #42
0
        public void TestBatchRemoval()
        {
            _store.EraseData();

            byte[] data = UTF8Encoding.UTF8.GetBytes("Hello world!");
            ResourceEntry <Binary> e = new ResourceEntry <Binary>();

            e.AuthorName = "Ewout";


            e.Resource = new Binary {
                Content = data, ContentType = "text/plain"
            };

            var rl = ResourceLocation.Build("binary", "3141");

            e.Id         = rl.ToUri();
            rl.VersionId = "1";
            e.SelfLink   = rl.ToUri();
            var batchGuid = Guid.NewGuid();

            ResourceEntry <Binary> result = (ResourceEntry <Binary>)_store.AddEntry(e, batchGuid);

            // Store 5 others with another batchguid
            batchGuid = Guid.NewGuid();

            for (int i = 0; i < 5; i++)
            {
                rl           = ResourceLocation.Build("binary", (10 + i).ToString());
                e.Id         = rl.ToUri();
                rl.VersionId = "1";
                e.SelfLink   = rl.ToUri();

                result = (ResourceEntry <Binary>)_store.AddEntry(e, batchGuid);
            }

            _store.PurgeBatch(batchGuid);

            var result2 = _store.ListCollection("binary");

            Assert.AreEqual(1, result2.Count());
            Assert.AreEqual("3141", ResourceLocation.GetIdFromResourceId(result2.First().Id));

            using (var s3 = new AmazonS3Storage())
            {
                s3.Open();
                var names = s3.ListNames();
                Assert.AreEqual(1, names.Length);
                Assert.IsTrue(names.First().Contains("3141"));
            }
        }
Beispiel #43
0
        public override void OnRebuild(VoidPtr address, int size, bool force)
        {
            BRESHeader *header = (BRESHeader *)address;

            *header = new BRESHeader(size, _numEntries + 1);

            ROOTHeader *rootHeader = header->First;

            *rootHeader = new ROOTHeader(_rootSize, Children.Count);

            ResourceGroup *pMaster = &rootHeader->_master;
            ResourceGroup *rGroup  = (ResourceGroup *)pMaster->EndAddress;

            //Write string table
            _stringTable.WriteTable(address + _strOffset);

            VoidPtr dataAddr = (VoidPtr)rootHeader + _rootSize;

            int gIndex = 1;

            foreach (BRESGroupNode g in Children)
            {
                ResourceEntry.Build(pMaster, gIndex++, rGroup, (BRESString *)_stringTable[g.Name]);

                *rGroup = new ResourceGroup(g.Children.Count);
                ResourceEntry *nEntry = rGroup->First;

                int rIndex = 1;
                foreach (BRESEntryNode n in g.Children)
                {
                    //Align data
                    dataAddr = ((int)dataAddr).Align(n.DataAlign);

                    ResourceEntry.Build(rGroup, rIndex++, dataAddr, (BRESString *)_stringTable[n.Name]);

                    //Rebuild entry
                    int len = n._calcSize;
                    n.Rebuild(dataAddr, len, force);
                    n.PostProcess(address, dataAddr, len, _stringTable);
                    dataAddr += len;
                }

                g._changed = false;

                //Advance to next group
                rGroup = (ResourceGroup *)rGroup->EndAddress;
            }

            _stringTable.Clear();
        }
Beispiel #44
0
        public static void SetupTest(TestContext ctx)
        {
            _import = new ExampleImporter();
            _import.ImportZip("examples.zip");

            _stockPatients = _import.ImportedEntries["patient"];
            _stockOrgs = _import.ImportedEntries["organization"];

            _stockPatient = (ResourceEntry)_stockPatients[0];
            _stockOrg = (ResourceEntry)_stockOrgs[0];

            _store = new MongoFhirStore();
            _store.EraseData();
        }
Beispiel #45
0
        protected internal override void PostProcess(VoidPtr bresAddress, VoidPtr dataAddress, int dataLength, StringTable stringTable)
        {
            base.PostProcess(bresAddress, dataAddress, dataLength, stringTable);

            SHP0v3 *header = (SHP0v3 *)dataAddress;

            if (_version == 4)
            {
                ((SHP0v4 *)dataAddress)->ResourceStringAddress = stringTable[Name] + 4;
                if (!String.IsNullOrEmpty(_originalPath))
                {
                    ((SHP0v4 *)dataAddress)->OrigPathAddress = stringTable[_originalPath] + 4;
                }
            }
            else
            {
                header->ResourceStringAddress = stringTable[Name] + 4;
                if (!String.IsNullOrEmpty(_originalPath))
                {
                    header->OrigPathAddress = stringTable[_originalPath] + 4;
                }
            }

            bint *stringPtr = header->StringEntries;

            for (int i = 0; i < header->_numEntries; i++)
            {
                stringPtr[i] = ((int)stringTable[_strings[i]] + 4) - (int)stringPtr;
            }

            ResourceGroup *group = header->Group;

            group->_first = new ResourceEntry(0xFFFF, 0, 0, 0, 0);

            ResourceEntry *rEntry = group->First;

            int index = 1;

            foreach (SHP0EntryNode n in Children)
            {
                dataAddress = (VoidPtr)group + (rEntry++)->_dataOffset;
                ResourceEntry.Build(group, index++, dataAddress, (BRESString *)stringTable[n.Name]);
                n.PostProcess(dataAddress, stringTable);
            }

            if (_version == 4)
            {
                _userEntries.PostProcess(((SHP0v4 *)dataAddress)->UserData, stringTable);
            }
        }
Beispiel #46
0
        //internal static ResourceEntry<Binary> CreateFromBinary(byte[] data, string mediaType, Uri id, DateTimeOffset updated, string title = null)
        //{
        //    var result = new ResourceEntry<Binary>();

        //    if (title == null)
        //        title = "Binary entry containing " + mediaType;

        //    initializeResourceEntry(result, id, updated, title);

        //    result.Content = new Binary() { Content = data, ContentType = mediaType };

        //    return result;
        //}

        private static void initializeResourceEntry(ResourceEntry member, Uri id, DateTimeOffset updated, string title)
        {
            member.Id          = id;
            member.LastUpdated = updated;
            member.Published   = DateTimeOffset.Now;    // Time copied into feed
            member.Title       = title;

            var userIdentity = System.Threading.Thread.CurrentPrincipal.Identity;

            member.AuthorName = userIdentity != null && !String.IsNullOrEmpty(userIdentity.Name) ?
                                userIdentity.Name : "(unauthenticated)";

            member.AuthorUri = null; //TODO: how to get a meaningful AuthorUri?
        }
Beispiel #47
0
        public void AffixTags(string collection, string id, IEnumerable <Tag> tags)
        {
            RequestValidator.ValidateCollectionName(collection);
            RequestValidator.ValidateId(id);
            if (tags == null)
            {
                throw new SparkException("No tags specified on the request");
            }

            ResourceEntry existing = this.internalRead(collection, id);

            existing.Tags = _importer.AffixTags(existing, tags);
            _store.ReplaceEntry(existing);
        }
        public static HttpResponseMessage ResourceResponse(this HttpRequestMessage request, ResourceEntry entry, HttpStatusCode? code=null)
        {
            request.SaveEntry(entry);

            HttpResponseMessage msg;

            if(code != null)
                msg = request.CreateResponse<ResourceEntry>(code.Value,entry);
            else
                msg = request.CreateResponse<ResourceEntry>(entry);

            msg.Headers.SetFhirTags(entry.Tags);
            return msg;
        }
Beispiel #49
0
        public HttpResponseMessage Validate(string type, ResourceEntry entry)
        {
            entry.Tags = Request.GetFhirTags();
            ResourceEntry <OperationOutcome> outcome = service.Validate(type, entry, null);

            if (outcome == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Created));
            }
            else
            {
                return(Request.ResourceResponse(outcome, (HttpStatusCode)422));
            }
        }
        protected internal virtual void PostProcess(VoidPtr scn0Address, VoidPtr dataAddress, StringTable stringTable)
        {
            ResourceGroup *group = (ResourceGroup *)dataAddress;

            group->_first = new ResourceEntry(0xFFFF, 0, 0, 0, 0);

            ResourceEntry *rEntry = group->First;

            int index = 1;

            foreach (SCN0EntryNode n in UsedChildren)
            {
                dataAddress = (VoidPtr)group + (rEntry++)->_dataOffset;
                ResourceEntry.Build(group, index++, dataAddress, (BRESString *)stringTable[n.Name]);
                //n.PostProcess(scn0Address, dataAddress, stringTable);
            }

            int len = 0;

            switch (_type)
            {
            case GroupType.LightSet:
                len = SCN0LightSet.Size;
                break;

            case GroupType.AmbientLight:
                len = SCN0AmbientLight.Size;
                break;

            case GroupType.Light:
                len = SCN0Light.Size;
                break;

            case GroupType.Fog:
                len = SCN0Fog.Size;
                break;

            case GroupType.Camera:
                len = SCN0Camera.Size;
                break;
            }
            bint *  hdr     = (bint *)scn0Address + 5;
            VoidPtr entries = scn0Address + hdr[(int)_type];

            foreach (SCN0EntryNode n in Children)
            {
                n.PostProcess(scn0Address, entries, stringTable);
                entries += len;
            }
        }
Beispiel #51
0
        public HttpResponseMessage Update(string type, string id, ResourceEntry entry)
        {
            entry.Tags = Request.GetFhirTags(); // todo: move to model binder?

            // ballot: Update is a mix between name from CRUD (only update no create) and functionality from Rest PUT (Create or update)
            ResourceEntry newEntry = service.Update(type, id, entry, null);

            if (newEntry != null)
            {
                return Request.StatusResponse(newEntry, HttpStatusCode.OK);
            }
            else
            {
                newEntry = service.Create(type, entry, id);
                return Request.StatusResponse(newEntry, HttpStatusCode.Created);
            }
        }
        public void ConstructEntry()
        {
            var pe = new ResourceEntry<Patient>(new Uri("http://www.nu.nl/fhir/Patient/1"), DateTimeOffset.Now, new Patient());
            Assert.IsNotNull(pe.Id);
            Assert.IsNotNull(pe.Title);
            Assert.IsNotNull(pe.LastUpdated);
            Assert.IsNotNull(pe.Resource);
            ModelValidator.Validate(pe);

            var b = new Bundle("A test feed", DateTimeOffset.Now);
            b.AuthorName = "Ewout";

            Assert.IsNotNull(pe.Id);
            Assert.IsNotNull(pe.Title);
            Assert.IsNotNull(pe.LastUpdated);
            b.Entries.Add(pe);
            ModelValidator.Validate(b);
        }
Beispiel #53
0
        public void ProfileAssertionHandling()
        {
            ResourceEntry<Patient> p = new ResourceEntry<Patient>();

            var prof1 = new Uri("http://profiles.com/important/profiles/1");
            var prof2 = new Uri("http://profiles.com/important/profiles/2");

            p.AddProfileAssertion(prof1);
            p.AddProfileAssertion(prof2);
            Assert.AreEqual(2, p.Tags.Count());

            Assert.IsTrue(p.GetAssertedProfiles().Contains(prof1));
            Assert.IsTrue(p.GetAssertedProfiles().Contains(prof2));

            p.RemoveProfileAssertion(prof2);
            Assert.IsTrue(p.GetAssertedProfiles().Contains(prof1));
            Assert.IsFalse(p.GetAssertedProfiles().Contains(prof2));
        }
Beispiel #54
0
        public void TestStoreBinaryEntry()
        {
            byte[] data = UTF8Encoding.UTF8.GetBytes("Hello world!");

            var e = new ResourceEntry<Binary>();

            e.AuthorName = "Ewout";
            e.Id = new Uri("binary/@3141", UriKind.Relative);
            e.Links.SelfLink = new Uri("binary/@3141/history/@1", UriKind.Relative);
            e.Resource = new Binary() { Content = data, ContentType = "text/plain" };

            // Test store
            var result = (ResourceEntry<Binary>)_store.AddEntry(e);

            Assert.IsNotNull(result.Resource);
            CollectionAssert.AreEqual(data, result.Resource.Content);
            Assert.AreEqual("text/plain", result.Resource.ContentType);

            // Test retrieve
            ResourceEntry<Binary> result2 = (ResourceEntry<Binary>)_store.FindEntryById(e.Id);
            Assert.IsNotNull(result2);
            CollectionAssert.AreEqual(e.Resource.Content, result2.Resource.Content);
            Assert.AreEqual(e.Resource.ContentType, result2.Resource.ContentType);

            // Test update
            byte[] data2 = UTF8Encoding.UTF8.GetBytes("Hello world!?");
            e.Resource = new Binary() { Content = data2, ContentType = "text/plain" };
            e.SelfLink = new Uri("binary/@3141/history/@2", UriKind.Relative);
            ResourceEntry<Binary> result3 = (ResourceEntry<Binary>)_store.AddEntry(e);
            Assert.IsNotNull(result3);
            Assert.AreEqual(e.Resource.ContentType, result3.Resource.ContentType);
            CollectionAssert.AreEqual(e.Resource.Content, result3.Resource.Content);

            // Test fetch latest
            ResourceEntry<Binary> result4 = (ResourceEntry<Binary>)_store.FindEntryById(e.Id);
            Assert.AreEqual(result4.Id, result3.Id);

            var allVersions = _store.ListVersionsById(e.Id);
            Assert.AreEqual(2, allVersions.Count());
            Assert.AreEqual(allVersions.First().Id, e.Id);
            Assert.AreEqual(allVersions.Skip(1).First().Id, result.Id);
        }
Beispiel #55
0
        public void WriteMetaData(ResourceEntry entry, int level, Resource resource)
        {
            if (level == 0)
            {
                Write(InternalField.ID, container_id);

                string selflink = entry.Links.SelfLink.ToString();
                Write(InternalField.SELFLINK, selflink);

                var resloc = new ResourceIdentity(container_id);
                Write(InternalField.JUSTID, resloc.Id);

                /*
                    //For testing purposes:
                    string term = resloc.Id;
                    List<Tag> tags = new List<Tag>() { new Tag(term, "http://tags.hl7.org", "labello"+term) } ;
                    tags.ForEach(Collect);
                /* */
                
                if (entry.Tags != null)
                {
                    entry.Tags.ToList().ForEach(Collect);
                }
                
            }
            else
            {
                
                string id = resource.Id;
                Write(InternalField.ID, container_id + "#" + id);
            }

            string category = resource.GetCollectionName();
                //ModelInfo.GetResourceNameForType(resource.GetType()).ToLower();
            Write(InternalField.RESOURCE, category);
            Write(InternalField.LEVEL, level);
        }
Beispiel #56
0
        public void UpdateEntries()
        {
            VoidPtr addr = _workingSource.Address + Header.EntriesChunkOffset;
            uint size1 = *(uint*)addr * 8 + 4;
            addr += size1;
            uint size2 = *(uint*)addr + 4;
            addr += size2;

            for (int i = 0; i < Header.EntryCount; i++)
            {
                if (ResourceEntries[i] == null)
                {
                    ResourceEntry* entry = (ResourceEntry*)addr;
                    *entry = new ResourceEntry()
                    {
                        offInPack = 0xBBBBBBBB,
                        nameOffsetEtc = 0xBBBBBBBB,
                        cmpSize = 0xBBBBBBBB,
                        decSize = 0xBBBBBBBB,
                        timestamp = 0xBBBBBBBB,
                        flags = 0xBBBBBBBB
                    };
                    addr += 0x18;
                }
                else
                {
                    ResourceEntry* entry = (ResourceEntry*)addr;
                    *entry = new ResourceEntry()
                    {
                        offInPack = ResourceEntries[i].OffInPack,
                        nameOffsetEtc = ResourceEntries[i].NameOffsetEtc,
                        cmpSize = ResourceEntries[i].CmpSize,
                        decSize = ResourceEntries[i].DecSize,
                        timestamp = ResourceEntries[i].Timestamp,
                        flags = ResourceEntries[i].Flags
                    };
                    addr += 0x18;
                }
            }
        }
 public void AssignResourceEntry(ResourceEntry resourceEntry)
 {
     _resourceEntry = resourceEntry;
     pictureBox1.Image = (Image)resourceEntry.Value;
 }
Beispiel #58
0
        public HttpResponseMessage Validate(string type, ResourceEntry entry)
        {
            entry.Tags = Request.GetFhirTags();
            ResourceEntry<OperationOutcome> outcome = service.Validate(type, entry, null);

            if (outcome == null)
                return Request.CreateResponse(HttpStatusCode.Created);
            else
                return Request.ResourceResponse(outcome, (HttpStatusCode)422);
        }
Beispiel #59
0
        public HttpResponseMessage Upsert(string type, string id, ResourceEntry entry)
        {
            entry.Tags = Request.GetFhirTags(); // todo: move to model binder?

            if (service.Exists(type, id))
            {
                ResourceEntry newEntry = service.Update(entry, type, id);
                return Request.StatusResponse(newEntry, HttpStatusCode.OK);
            }
            else
            {
                ResourceEntry newEntry = service.Create(entry, type, id);
                return Request.StatusResponse(newEntry, HttpStatusCode.Created);
            }
        }
 public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
 {
     this.entry = request.GetEntry();
     return base.GetPerRequestFormatterInstance(type, request, mediaType);
 }