Exemple #1
0
        private ThingCollection GetResultGroupFromResponse(
            string groupName,
            HealthRecordAccessor accessor,
            ThingQuery matchingQuery,
            XPathNavigator groupNavigator)
        {
            ThingCollection result =
                new ThingCollection(groupName, accessor, matchingQuery, _connection);

            int maxResultsPerRequest = 0;

            XPathNodeIterator thingNodeIterator = groupNavigator.Select("thing");
            XPathNodeIterator unprocessedThingKeyInfoNodeIterator = groupNavigator.Select("unprocessed-thing-key-info");

            XPathNavigator filteredNodeNavigator       = groupNavigator.SelectSingleNode("filtered");
            XPathNavigator orderByCultureNodeNavigator = groupNavigator.SelectSingleNode("order-by-culture");

            if (thingNodeIterator != null)
            {
                foreach (XPathNavigator thingNode in thingNodeIterator)
                {
                    ThingBase resultThingBase = DeserializeItem(thingNode);

                    result.AddResult(resultThingBase);

                    maxResultsPerRequest++;
                }
            }

            if (unprocessedThingKeyInfoNodeIterator != null)
            {
                foreach (XPathNavigator unprocessedThingKeyInfoNode in unprocessedThingKeyInfoNodeIterator)
                {
                    XPathNavigator thingIdNavigator = unprocessedThingKeyInfoNode.SelectSingleNode("thing-id");

                    Guid thingId      = Guid.Parse(thingIdNavigator.Value);
                    Guid versionStamp = Guid.Parse(thingIdNavigator.GetAttribute("version-stamp", string.Empty));

                    ThingKey key = new ThingKey(thingId, versionStamp);
                    result.AddResult(key);
                }
            }

            if (filteredNodeNavigator != null)
            {
                result.WasFiltered = filteredNodeNavigator.ValueAsBoolean;
            }

            if (orderByCultureNodeNavigator != null)
            {
                result.OrderByCulture = orderByCultureNodeNavigator.Value;
            }

            if (maxResultsPerRequest > 0)
            {
                result.MaxResultsPerRequest = maxResultsPerRequest;
            }

            return(result);
        }
Exemple #2
0
        public IReadOnlyCollection <ThingCollection> Deserialize(
            HealthServiceResponseData responseData,
            HealthRecordSearcher searcher)
        {
            XPathNavigator navigator = responseData.InfoNavigator;

            Collection <ThingCollection> result = new Collection <ThingCollection>();

            if (navigator != null)
            {
                XPathNodeIterator groupNodeIterator = navigator.Select("//group");

                foreach (XPathNavigator groupNavigator in groupNodeIterator)
                {
                    ThingCollection resultGroup = CreateResultGroupFromResponse(
                        searcher.Record,
                        groupNavigator,
                        searcher.Filters);

                    if (resultGroup != null)
                    {
                        result.Add(resultGroup);
                    }
                }
            }

            return(new ReadOnlyCollection <ThingCollection>(result));
        }
        public async Task <IReadOnlyCollection <T> > GetThingsAsync <T>(Guid recordId, ThingQuery query = null)
            where T : IThing
        {
            Validator.ThrowIfArgumentNull(recordId, nameof(recordId), Resources.NewItemsNullItem);

            // Ensure that we have a query that requests the correct type
            T thing = (T)Activator.CreateInstance(typeof(T));

            query = query ?? new ThingQuery();
            query.TypeIds.Clear();
            query.TypeIds.Add(thing.TypeId);

            ThingCollection results = await GetThingsAsync(recordId, query);

            IList <T> things = new Collection <T>();

            foreach (IThing resultThing in results)
            {
                if (resultThing is T)
                {
                    things.Add((T)resultThing);
                }
            }

            return(new ReadOnlyCollection <T>(things));
        }
        public void WhenUnProcessedKeyIsPresent()
        {
            string thing =
                @"<thing><thing-id version-stamp=""583a502e-69a1-4546-be74-dc2ba8db7d98"">e4bfb506-e94e-4d69-ba04-0c12197c0bb8</thing-id><type-id name=""Exercise"">85a21ddb-db20-4c65-8d30-33c899ccf612</type-id><thing-state>Active</thing-state><flags>0</flags><eff-date>2017-01-31T20:00:00</eff-date><created><timestamp>2017-02-01T00:55:06.92Z</timestamp><app-id name=""HealthVault Insights"">52e62dc1-0834-4e25-9612-36f6692a9bcf</app-id><person-id name=""Test"">b54d4b92-9e05-4f60-a428-8b6262d18ec7</person-id><access-avenue>Offline</access-avenue><audit-action>Created</audit-action></created><updated><timestamp>2017-02-01T00:55:06.92Z</timestamp><app-id name=""HealthVault Insights"">52e62dc1-0834-4e25-9612-36f6692a9bcf</app-id><person-id name=""Test"">b54d4b92-9e05-4f60-a428-8b6262d18ec7</person-id><access-avenue>Offline</access-avenue><audit-action>Created</audit-action></updated><data-xml><exercise><when><structured><date><y>2017</y><m>1</m><d>31</d></date><time><h>20</h><m>0</m><s>0</s><f>0</f></time></structured></when><activity><text>Bicycling</text><code><value>Bicycling</value><family>wc</family><type>exercise-activities</type><version>1</version></code></activity><duration>120</duration><detail><name><value>CaloriesBurned_calories</value><family>wc</family><type>exercise-detail-names</type><version>1</version></name><value><value>544</value><units><text>Calories</text><code><value>Calories</value><family>wc</family><type>exercise-units</type><version>1</version></code></units></value></detail><detail><name><value>ElevationGain_meters</value><family>wc</family><type>exercise-detail-names</type><version>1</version></name><value><value>0</value><units><text>meters</text><code><value>Meters</value><family>wc</family><type>exercise-units</type><version>1</version></code></units></value></detail><detail><name><value>ElevationLoss_meters</value><family>wc</family><type>exercise-detail-names</type><version>1</version></name><value><value>0</value><units><text>meters</text><code><value>Meters</value><family>wc</family><type>exercise-units</type><version>1</version></code></units></value></detail></exercise><common><source>Microsoft HealthVault Insights</source><client-thing-id>Biking_a01442b7-213e-4ccf-b057-bf00fb809b46_636214896000000000-Duration</client-thing-id></common></data-xml><eff-permissions immutable=""false""><permission>Read</permission><permission>Update</permission><permission>Create</permission><permission>Delete</permission></eff-permissions></thing>";
            string unprocessedThingKeyInfo =
                @"<unprocessed-thing-key-info><thing-id version-stamp=""583a502e-69a1-4546-be74-dc2ba8db7d98"">e4bfb506-e94e-4d69-ba04-0c12197c0bb8</thing-id></unprocessed-thing-key-info>";

            string xml = $"<group>{thing}{unprocessedThingKeyInfo}</group>";

            HealthRecordSearcher query = new HealthRecordSearcher(_healthRecordAccessor);

            HealthServiceResponseData responseData = new HealthServiceResponseData
            {
                InfoNavigator = new XPathDocument(new StringReader(xml)).CreateNavigator()
            };

            IReadOnlyCollection <ThingCollection> thingCollections = _thingDeserializer.Deserialize(responseData, query);

            ThingCollection thingCollection = thingCollections.FirstOrDefault();

            // validate that we have both thing and unprocessed thing is parsed
            Assert.AreEqual(2, thingCollection.Count);

            // validate that the max full thing is 1 and doesn't include partial item
            Assert.AreEqual(1, thingCollection.MaxResultsPerRequest);
        }
        public async Task MultipleQueries()
        {
            IHealthVaultSodaConnection connection = HealthVaultConnectionFactory.Current.GetOrCreateSodaConnection(Constants.Configuration);
            IThingClient thingClient = connection.CreateThingClient();
            PersonInfo   personInfo  = await connection.GetPersonInfoAsync();

            HealthRecordInfo record = personInfo.SelectedRecord;

            await DeletePreviousThings(thingClient, record);

            LocalDateTime nowLocal = SystemClock.Instance.GetCurrentInstant().InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()).LocalDateTime;

            var bloodGlucose = new BloodGlucose(
                new HealthServiceDateTime(nowLocal),
                new BloodGlucoseMeasurement(
                    4.2,
                    new DisplayValue(4.2, "mmol/L", "mmol-per-l")),
                new CodableValue("Whole blood", "wb", new VocabularyKey("glucose-measurement-type", "wc", "1")));

            var weight = new Weight(
                new HealthServiceDateTime(nowLocal),
                new WeightValue(81, new DisplayValue(81, "KG", "kg")));

            await thingClient.CreateNewThingsAsync(
                record.Id,
                new List <IThing>
            {
                bloodGlucose,
                weight,
            });

            var resultSet = await thingClient.GetThingsAsync(record.Id, new[] { new ThingQuery(BloodGlucose.TypeId), new ThingQuery(Weight.TypeId) });

            Assert.AreEqual(2, resultSet.Count);
            var resultList = resultSet.ToList();

            ThingCollection glucoseCollection    = resultList[0];
            var             returnedBloodGlucose = (BloodGlucose)glucoseCollection.First();

            Assert.AreEqual(bloodGlucose.Value.Value, returnedBloodGlucose.Value.Value);

            ThingCollection weightCollection = resultList[1];
            var             returnedWeight   = (Weight)weightCollection.First();

            Assert.AreEqual(weight.Value.Kilograms, returnedWeight.Value.Kilograms);
        }
        public async Task <T> GetThingAsync <T>(Guid recordId, Guid thingId)
            where T : IThing
        {
            Validator.ThrowIfArgumentNull(recordId, nameof(recordId), Resources.NewItemsNullItem);

            // Create a new searcher to get the item.
            HealthRecordAccessor accessor = new HealthRecordAccessor(_connection, recordId);
            HealthRecordSearcher searcher = new HealthRecordSearcher(accessor);

            ThingQuery query = new ThingQuery();

            query.ItemIds.Add(thingId);
            query.View.Sections      = ThingSections.Default;
            query.CurrentVersionOnly = true;

            HealthServiceResponseData result = await GetRequestWithParameters(recordId, searcher, new[] { query });

            IReadOnlyCollection <ThingCollection> resultSet = _thingDeserializer.Deserialize(result, searcher);

            // Check in case HealthVault returned invalid data.
            if (resultSet.Count == 0)
            {
                return(default(T));
            }

            if (resultSet.Count > 1 || resultSet.ElementAt(0).Count > 1)
            {
                throw new MoreThanOneThingException(Resources.GetSingleThingTooManyResults);
            }

            if (resultSet.Count == 1)
            {
                ThingCollection resultGroup = resultSet.ElementAt(0);

                if (resultGroup.Count == 1)
                {
                    return((T)resultGroup[0]);
                }
            }

            return(default(T));
        }
Exemple #7
0
        static void Main(string[] args)
        {
            using (localhost.HelloIndigoServiceClient proxy = new Client.localhost.HelloIndigoServiceClient())
            {
                ThingCollection things = new ThingCollection();
                Thing           thing1 = new Thing();
                thing1.Name        = "Thing1";
                thing1.Description = "I am Thing1";
                Thing thing2 = new Thing();
                thing2.Name        = "Thing2";
                thing2.Description = "I am Thing2";

                things.Add(thing1);
                things.Add(thing2);
                proxy.SaveThings(things);

                things = proxy.GetThings();
            }

            Console.WriteLine("Press <ENTER> to terminate Client.");
            Console.ReadLine();
        }
Exemple #8
0
    public static void Main(string[] args)
    {
        Thing a = new Thing(1, 'z', DateTime.Now);
        Thing b = new Thing(2, 'y', DateTime.Now.AddDays(1));
        Thing c = new Thing(3, 'x', DateTime.Now.AddDays(-1));
        Thing d = new Thing(4, 'w', DateTime.Now.AddDays(2));
        Thing e = new Thing(5, 'v', DateTime.Now.AddDays(-2));

        ThingCollection tc = new ThingCollection();

        tc.AddRange(new Thing[] { a, b, c, d, e });

        Thing result;

        //Max by date
        result = tc.Aggregate(tc[0],
                              delegate(Thing Best, Thing Candidate)
        {
            return((Candidate.theDateTime.CompareTo(
                        Best.theDateTime) > 0) ?
                   Candidate :
                   Best);
        }
                              );
        Console.WriteLine("Max by date: {0}", result.Dump());

        //Min by char
        result = tc.Aggregate(tc[0],
                              delegate(Thing Best, Thing Candidate)
        {
            return((Candidate.theChar < Best.theChar) ?
                   Candidate :
                   Best);
        }
                              );
        Console.WriteLine("Min by char: {0}", result.Dump());
    }
        public async Task MultipleThingTypes()
        {
            IHealthVaultSodaConnection connection = HealthVaultConnectionFactory.Current.GetOrCreateSodaConnection(Constants.Configuration);
            IThingClient thingClient = connection.CreateThingClient();
            PersonInfo   personInfo  = await connection.GetPersonInfoAsync();

            HealthRecordInfo record = personInfo.SelectedRecord;

            await DeletePreviousThings(thingClient, record);

            LocalDateTime nowLocal = SystemClock.Instance.GetCurrentInstant().InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()).LocalDateTime;

            var bloodGlucose = new BloodGlucose(
                new HealthServiceDateTime(nowLocal),
                new BloodGlucoseMeasurement(
                    4.2,
                    new DisplayValue(4.2, "mmol/L", "mmol-per-l")),
                new CodableValue("Whole blood", "wb", new VocabularyKey("glucose-measurement-type", "wc", "1")));

            var weight = new Weight(
                new HealthServiceDateTime(nowLocal),
                new WeightValue(81, new DisplayValue(81, "KG", "kg")));

            var bloodPressure1 = new BloodPressure
            {
                EffectiveDate = nowLocal,
                Systolic      = 110,
                Diastolic     = 90,
            };

            var bloodPressure2 = new BloodPressure
            {
                EffectiveDate = nowLocal.PlusHours(-1),
                Systolic      = 111,
                Diastolic     = 91,
            };

            var cholesterolProfile = new CholesterolProfileV2
            {
                When         = new HealthServiceDateTime(nowLocal),
                LDL          = new ConcentrationMeasurement(110),
                HDL          = new ConcentrationMeasurement(65),
                Triglyceride = new ConcentrationMeasurement(140)
            };

            var labTestResult = new LabTestResults(new LabTestResultGroup[] { new LabTestResultGroup(new CodableValue("test")) });

            var immunization = new Immunization(new CodableValue("diphtheria, tetanus toxoids and acellular pertussis vaccine", "DTaP", new VocabularyKey("immunizations", "wc", "1")));

            var procedure = new Procedure(new CodableValue("A surgery"));

            var allergy = new Allergy(new CodableValue("Pollen"));

            var condition = new Condition(new CodableValue("Diseased"));

            await thingClient.CreateNewThingsAsync(
                record.Id,
                new List <IThing>
            {
                bloodGlucose,
                weight,
                bloodPressure1,
                bloodPressure2,
                cholesterolProfile,
                labTestResult,
                immunization,
                procedure,
                allergy,
                condition
            });

            var             query           = CreateMultiThingQuery();
            ThingCollection thingCollection = await thingClient.GetThingsAsync(record.Id, query);

            Assert.AreEqual(10, thingCollection.Count);

            var returnedBloodGlucose = (BloodGlucose)thingCollection.First(t => t.TypeId == BloodGlucose.TypeId);

            Assert.AreEqual(bloodGlucose.Value.Value, returnedBloodGlucose.Value.Value);

            var returnedWeight = (Weight)thingCollection.First(t => t.TypeId == Weight.TypeId);

            Assert.AreEqual(weight.Value.Kilograms, returnedWeight.Value.Kilograms);

            var returnedBloodPressures = thingCollection.Where(t => t.TypeId == BloodPressure.TypeId).Cast <BloodPressure>().ToList();

            Assert.AreEqual(2, returnedBloodPressures.Count);

            Assert.AreEqual(bloodPressure1.Systolic, returnedBloodPressures[0].Systolic);
        }
Exemple #10
0
        /// <summary>
        /// Gets the user's PersonalImage from HealthVault and stores in a local file.
        /// </summary>
        /// <param name="recordInfo"></param>
        /// <param name="things"></param>
        /// <returns></returns>
        private static async Task <Windows.Storage.StorageFile> GetAndSavePersonalImage(HealthRecordInfo recordInfo, ThingCollection things)
        {
            var fileName = recordInfo.DisplayName + ".jpg";
            var file     = await Windows.Storage.ApplicationData.Current.LocalCacheFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.OpenIfExists);

            if (things.Count > 0)
            {
                var personalImage = (PersonalImage)things.First();

                using (Stream currentImage = personalImage.ReadImage())
                {
                    if (currentImage != null)
                    {
                        byte[] imageBytes = new byte[currentImage.Length];
                        await currentImage.ReadAsync(imageBytes, 0, (int)currentImage.Length);

                        using (var writeStream = await file.OpenStreamForWriteAsync())
                        {
                            await writeStream.WriteAsync(imageBytes, 0, (int)currentImage.Length);
                        }
                    }
                }
            }

            return(file);
        }
Exemple #11
0
 public void SaveThings(ThingCollection collection)
 {
     Console.WriteLine("Saving {0} things.", collection.Count);
     m_things = collection;
 }