private async Task <XPathNavigator> GetPartialThings(
            HealthRecordAccessor record,
            IList <ThingKey> thingKeys,
            int currentThingKeyIndex,
            int numberOfFullThingsToRetrieve)
        {
            HealthRecordSearcher searcher = record.CreateSearcher();
            ThingQuery           query    = new ThingQuery();

            for (int i = currentThingKeyIndex;
                 i < thingKeys.Count &&
                 i < currentThingKeyIndex + numberOfFullThingsToRetrieve;
                 i++)
            {
                query.ItemKeys.Add(thingKeys[i]);
            }
            query.View               = this.Query.View;
            query.States             = this.Query.States;
            query.CurrentVersionOnly = this.Query.CurrentVersionOnly;
            if (Query.OrderByClauses.Count > 0)
            {
                foreach (var orderByClause in Query.OrderByClauses)
                {
                    query.OrderByClauses.Add(orderByClause);
                }
            }

            searcher.Filters.Add(query);

            return(await searcher.GetMatchingItemsRaw().ConfigureAwait(false));
        }
        /// <summary>
        /// Obtains Weight objects from HealthVault
        /// </summary>
        /// <returns></returns>
        public override async Task Initialize(NavigationParams navParams)
        {
            //Save the connection so that we can reuse it for updates later
            _connection = navParams.Connection;

            HealthRecordInfo recordInfo  = (await _connection.GetPersonInfoAsync()).SelectedRecord;
            IThingClient     thingClient = _connection.CreateThingClient();

            if (QueryTimeframe.SelectedIndex == (int)QueryTimeframeEnum.Default)
            {
                //Uses a simple query which specifies the Thing type as the only filter
                Items = await thingClient.GetThingsAsync <Weight>(recordInfo.Id);
            }
            else if (QueryTimeframe.SelectedIndex == (int)QueryTimeframeEnum.Last30d)
            {
                //In this mode, the app specifies a ThingQuery which can be used for functions like
                //filtering, or paging through values
                ThingQuery query = new ThingQuery()
                {
                    EffectiveDateMin = DateTime.Now.AddDays(-30)
                };

                Items = await thingClient.GetThingsAsync <Weight>(recordInfo.Id, query);
            }

            OnPropertyChanged("Items");
            OnPropertyChanged("Latest");

            return;
        }
Exemplo n.º 3
0
        private ThingCollection CreateResultGroupFromResponse(
            HealthRecordAccessor accessor,
            XPathNavigator groupNavigator,
            Collection <ThingQuery> queryFilters)
        {
            Validator.ThrowIfArgumentNull(accessor, nameof(accessor), Resources.ResponseRecordNull);

            // Name is optional
            ThingQuery matchingQuery = null;
            string     groupName     = groupNavigator.GetAttribute("name", string.Empty);

            foreach (ThingQuery queryFilter in queryFilters)
            {
                if (string.IsNullOrEmpty(queryFilter.Name) && string.IsNullOrEmpty(groupName))
                {
                    matchingQuery = queryFilter;
                    break;
                }

                if (string.Equals(queryFilter.Name, groupName, StringComparison.Ordinal))
                {
                    matchingQuery = queryFilter;
                    break;
                }
            }

            return(GetResultGroupFromResponse(groupName, accessor, matchingQuery, groupNavigator));
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
        private ThingQuery GetWeightThingQuery()
        {
            var config = Substitute.For <HealthVaultConfiguration>();
            var query  = new ThingQuery(config);

            query.ItemIds.Add(Weight.TypeId);
            return(query);
        }
        public async Task <ThingCollection> GetThingsAsync(Guid recordId, ThingQuery query)
        {
            Validator.ThrowIfGuidEmpty(recordId, nameof(recordId));
            Validator.ThrowIfArgumentNull(query, nameof(query));

            IReadOnlyCollection <ThingCollection> resultSet = await this.GetThingsAsync(recordId, new[] { query }).ConfigureAwait(false);

            return(resultSet.FirstOrDefault());
        }
Exemplo n.º 7
0
        public void Should_get_all(ThingQuery.GetAll request)
        {
            //  Arrange

            //  Act
            var result = _mediator.SendAsync(request).Result;

            //  Assert
            result.Count.ShouldEqual(4);
        }
Exemplo n.º 8
0
        public void Should_get_all(ThingQuery.GetAll request)
        {
            //  Arrange

            //  Act
            var response = _httpClient.GetAsync("/api/thing").Result;

            //  Assert
            response.StatusCode.ShouldEqual(HttpStatusCode.OK);
        }
Exemplo n.º 9
0
        public void Should_get_one(ThingQuery.GetById request)
        {
            //  Arrange
            request.Id = "my-first";

            //  Act
            var result = _mediator.SendAsync(request).Result;

            //  Assert
            result.Id.ShouldEqual(request.Id);
        }
        /// <summary>
        /// Creates a new instance of the <see cref="ThingDataTable"/>
        /// class with the specified table view and filter.
        /// </summary>
        ///
        /// <param name="view">
        /// The view that the data table should take on the data.
        /// </param>
        ///
        /// <param name="query">
        /// The filter used to gather things from the HealthVault
        /// service.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="query"/> parameter is <b>null</b>.
        /// </exception>
        ///
        /// <exception cref="ArgumentException">
        /// The <paramref name="view"/> parameter is
        /// <see cref="ThingDataTableView.SingleTypeTable"/> and
        /// the <paramref name="query"/> parameter contains more than one type
        /// identifier.
        /// </exception>
        public ThingDataTable(
            ThingDataTableView view,
            ThingQuery query)
        {
            Validator.ThrowIfArgumentNull(query, nameof(query), Resources.DataTableFilterNull);

            if (view == ThingDataTableView.SingleTypeTable && query.TypeIds.Count > 1)
            {
                throw new ArgumentException(Resources.DataTableViewInvalid, nameof(view));
            }

            this.query = query;
            _view      = view;
        }
Exemplo n.º 11
0
        public async Task GetThings()
        {
            InitializeResponse(SampleUtils.GetSampleContent("ThingsSampleBloodPressure.xml"));
            ThingQuery query  = this.GetBloodPressureThingQuery();
            var        result = await _client.GetThingsAsync(_recordId, query);

            // ensure that the connection was called with the proper values
            await _connection.Received().ExecuteAsync(
                HealthVaultMethods.GetThings,
                Arg.Any <int>(),
                Arg.Is <string>(x => x.Contains(BloodPressure.TypeId.ToString())),
                Arg.Is <Guid>(x => x == _recordId));

            // Assert that all results are parsed, grouped, and returned correctly.
            // Note that the sample data was not from this exact call, so it includes some other types of things in the results
            Assert.AreEqual(33, result.Count);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the user's PersonalImage Things and then calls GetAndSavePersonalImage to extract the blob,
        /// save to disk, then adds that path to the ImageSource property so the UX can find it.
        /// </summary>
        /// <param name="recordInfo"></param>
        /// <param name="thingClient"></param>
        /// <returns></returns>
        private async Task GetPersonalImageAsync(HealthRecordInfo recordInfo, IThingClient thingClient)
        {
            //Build query
            var query = new ThingQuery(new Guid[] { PersonalImage.TypeId });

            query.View.Sections = ThingSections.Xml | ThingSections.BlobPayload | ThingSections.Signature;

            var things = await thingClient.GetThingsAsync(recordInfo.Id, query);

            if (things.Count > 0)
            {
                Windows.Storage.StorageFile file = await GetAndSavePersonalImage(recordInfo, things);

                ImageSource = file.Path;
                OnPropertyChanged("ImageSource");
            }
        }
Exemplo n.º 13
0
        public void Should_throw_ex_when_id_not_exists(ThingQuery.GetById request)
        {
            try
            {
                //  Arrange

                //  Act
                _mediator.SendAsync(request).Wait();
            }
            catch (AggregateException ex)
            {
                //  Assert
                ex.InnerException.ShouldBeType(typeof (EntityNotFound));
                return;
            }

            throw new AssertException();
        }
        public override async Task Initialize(NavigationParams navParams)
        {
            HealthRecordInfo recordInfo  = (await navParams.Connection.GetPersonInfoAsync()).SelectedRecord;
            IThingClient     thingClient = navParams.Connection.CreateThingClient();

            var query = new ThingQuery(new Guid[] { BloodGlucose.TypeId, Weight.TypeId, BloodPressure.TypeId, CholesterolProfile.TypeId,
                                                    LabTestResults.TypeId, Immunization.TypeId, Procedure.TypeId, Allergy.TypeId, Condition.TypeId });

            var items = await thingClient.GetThingsAsync(recordInfo.Id, query);

            //Create a grouped view of the Things by type
            Groups = from colItem in items
                     orderby(colItem as ThingBase).TypeName, (colItem as ThingBase).EffectiveDate descending
            group colItem by(colItem as ThingBase).TypeName into newGroup
            select newGroup;

            OnPropertyChanged("Groups");
        }
Exemplo n.º 15
0
        private async Task <ImageSource> GetImageAsync()
        {
            var query = new ThingQuery(PersonalImage.TypeId)
            {
                View = { Sections = ThingSections.Xml | ThingSections.BlobPayload | ThingSections.Signature }
            };

            var things = await _thingClient.GetThingsAsync(_recordId, query);

            IThing firstThing = things?.FirstOrDefault();

            if (firstThing == null)
            {
                return(null);
            }
            PersonalImage image = (PersonalImage)firstThing;

            return(ImageSource.FromStream(() => image.ReadImage()));
        }
        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));
        }
Exemplo n.º 17
0
        private async void GetUserImage_OnClick(object sender, RoutedEventArgs e)
        {
            PersonInfo personInfo = await _connection.GetPersonInfoAsync();

            HealthRecordInfo recordInfo = personInfo.SelectedRecord;

            IThingClient thingClient = _connection.CreateThingClient();
            ThingQuery   query       = new ThingQuery();

            query.View.Sections = ThingSections.Default | ThingSections.BlobPayload;
            var theThings = await thingClient.GetThingsAsync <PersonalImage>(recordInfo.Id, query);

            Stream imageStream = theThings.First().ReadImage();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                await imageStream.CopyToAsync(memoryStream);

                OutputBlock.Text = $"Image has {memoryStream.Length} bytes";
            }
        }
Exemplo n.º 18
0
        public async Task UsingDatesInThingsQueryReturnProperly()
        {
            IHealthVaultSodaConnection connection = HealthVaultConnectionFactory.Current.GetOrCreateSodaConnection(Constants.Configuration);
            IThingClient thingClient = connection.CreateThingClient();
            PersonInfo   personInfo  = await connection.GetPersonInfoAsync();

            HealthRecordInfo record = personInfo.SelectedRecord;

            ThingQuery query = new ThingQuery(BloodGlucose.TypeId);
            var        now   = DateTime.UtcNow;

            query.CreatedDateMin    = Instant.FromDateTimeUtc(now.AddDays(-5));
            query.CreatedDateMax    = Instant.FromDateTimeUtc(now.AddDays(-4));
            query.UpdatedDateMin    = Instant.FromDateTimeUtc(now.AddDays(-3));
            query.UpdatedDateMax    = Instant.FromDateTimeUtc(now.AddDays(-2));
            query.UpdatedEndDateMin = LocalDateTime.FromDateTime(now.AddDays(-1));
            query.UpdatedEndDateMax = LocalDateTime.FromDateTime(now);

            var results = await thingClient.GetThingsAsync(record.Id, query);

            Assert.IsNotNull(results);
            Assert.IsNotNull(results.Query);
            Assert.IsNotNull(results.Query.CreatedDateMin);
            Assert.AreEqual(results.Query.CreatedDateMin.Value.ToDateTimeUtc(), now.AddDays(-5));

            Assert.IsNotNull(results.Query.CreatedDateMax);
            Assert.AreEqual(results.Query.CreatedDateMax.Value.ToDateTimeUtc(), now.AddDays(-4));

            Assert.IsNotNull(results.Query.UpdatedDateMin);
            Assert.AreEqual(results.Query.UpdatedDateMin.Value.ToDateTimeUtc(), now.AddDays(-3));

            Assert.IsNotNull(results.Query.UpdatedDateMax);
            Assert.AreEqual(results.Query.UpdatedDateMax.Value.ToDateTimeUtc(), now.AddDays(-2));

            Assert.IsNotNull(results.Query.UpdatedEndDateMin);
            Assert.AreEqual(results.Query.UpdatedEndDateMin.Value, LocalDateTime.FromDateTime(now.AddDays(-1)));

            Assert.IsNotNull(results.Query.UpdatedEndDateMax);
            Assert.AreEqual(results.Query.UpdatedEndDateMax.Value, LocalDateTime.FromDateTime(now));
        }
Exemplo n.º 19
0
        public async Task GetThingsPaged()
        {
            InitializeResponse(
                SampleUtils.GetSampleContent("ThingsPagedResult1.xml"),
                SampleUtils.GetSampleContent("ThingsPagedResult2.xml"),
                SampleUtils.GetSampleContent("ThingsPagedResult3.xml"));

            ThingQuery query  = this.GetBloodPressureThingQuery();
            var        result = await _client.GetThingsAsync <BloodPressure>(_recordId, query);

            List <BloodPressure> resultList = result.ToList();

            // The first call should be a normal one to get blood pressures.
            await _connection.Received().ExecuteAsync(
                HealthVaultMethods.GetThings,
                Arg.Any <int>(),
                Arg.Is <string>(x => x.Contains(BloodPressure.TypeId.ToString())),
                Arg.Is <Guid>(x => x == _recordId));

            // The first response contains some unresolved items, which need another couple of calls to fetch.
            // We make sure we see these calls and the thing IDs they are requesting.
            await _connection.Received().ExecuteAsync(
                HealthVaultMethods.GetThings,
                Arg.Any <int>(),
                Arg.Is <string>(x => x.Contains("c0464a97-2832-4f50-a683-6d98c396da08")),
                Arg.Is <Guid>(x => x == _recordId));

            await _connection.Received().ExecuteAsync(
                HealthVaultMethods.GetThings,
                Arg.Any <int>(),
                Arg.Is <string>(x => x.Contains("f5f2c6f0-6924-4744-9338-8e3d81c31259")),
                Arg.Is <Guid>(x => x == _recordId));

            Assert.AreEqual(503, result.Count);

            BloodPressure lastBloodPressure = resultList[502];

            Assert.AreEqual(117, lastBloodPressure.Systolic);
            Assert.AreEqual(70, lastBloodPressure.Diastolic);
        }
        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));
        }