internal static string GetParametersXml(HealthRecordSearcher searcher)
        {
            if (searcher.Filters.Count == 0)
            {
                HealthServiceResponseError error = new HealthServiceResponseError
                {
                    Message = Resources.HealthRecordSearcherNoFilters
                };

                HealthServiceException e =
                    HealthServiceExceptionHelper.GetHealthServiceException(
                        HealthServiceStatusCode.InvalidFilter, error);
                throw e;
            }

            StringBuilder parameters = new StringBuilder(128);

            XmlWriterSettings settings = SDKHelper.XmlUnicodeWriterSettings;

            using (XmlWriter writer = XmlWriter.Create(parameters, settings))
            {
                foreach (ThingQuery filter in searcher.Filters)
                {
                    // Add all filters
                    filter.AddFilterXml(writer);
                }

                writer.Flush();
            }

            return(parameters.ToString());
        }
Example #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));
        }
Example #3
0
        public static JObject GetAllThings(Guid personId, Guid recordId)
        {
            Guid appId = new Guid(Connections.ApplicationId);
            OfflineWebApplicationConnection connection = Connections.CreateConnection(appId, personId);

            HealthRecordAccessor accessor = new HealthRecordAccessor(connection, recordId);
            HealthRecordSearcher searcher = new HealthRecordSearcher(accessor);

            List <Guid> queryOrder = Types.TypeDefinitions.Keys.ToList();

            queryOrder.Add(CustomType.Id);

            foreach (Guid thingType in queryOrder)
            {
                HealthRecordFilter filter = new HealthRecordFilter(thingType);
                if (thingType.Equals(CustomType.Id) || (Types.TypeDefinitions.ContainsKey(thingType) && !Types.TypeDefinitions[thingType].Persistent))
                {
                    filter.EffectiveDateMin = GetMinTime();
                }
                searcher.Filters.Add(filter);
            }

            ReadOnlyCollection <HealthRecordItemCollection> things = searcher.GetMatchingItems();

            return(TransformThings(things, queryOrder));
        }
        public static List <string> GetThings(OfflineWebApplicationConnection connection,
                                              Guid recordId, Guid[] typeIds, DateTime updatedSinceUtc)
        {
            HealthRecordAccessor record   = new HealthRecordAccessor(connection, recordId);
            HealthRecordSearcher searcher = record.CreateSearcher();
            HealthRecordFilter   filter   = new HealthRecordFilter();

            searcher.Filters.Add(filter);

            foreach (Guid typeId in typeIds)
            {
                filter.TypeIds.Add(typeId);
            }

            filter.UpdatedDateMin = DateTime.SpecifyKind(updatedSinceUtc, DateTimeKind.Utc);

            filter.View.Sections = HealthRecordItemSections.All | Microsoft.Health.HealthRecordItemSections.Xml;

            //HealthRecordItemSections.Core |
            //HealthRecordItemSections.Xml |
            //HealthRecordItemSections.Audits;

            HealthRecordItemCollection things = searcher.GetMatchingItems()[0];

            List <string> items = new List <string>();

            foreach (HealthRecordItem thing in things)
            {
                items.Add(thing.GetItemXml(filter.View.Sections));
            }
            return(items);
        }
Example #5
0
    protected void Btn_ShowWeeklyReadingsTextSummary_Click(object sender, System.EventArgs e)
    {
        HealthRecordSearcher searcher = PersonInfo.SelectedRecord.CreateSearcher();
        HealthRecordFilter   filter   = new HealthRecordFilter(
            Emotion.TypeId,
            DietaryDailyIntake.TypeId,
            Weight.TypeId,
            SleepJournalAM.TypeId,
            Exercise.TypeId);

        filter.EffectiveDateMin = DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0));
        searcher.Filters.Add(filter);
        filter.View.TransformsToApply.Add("mtt");

        HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

        DataTable dataTable = new DataTable();

        dataTable.Columns.Add(new DataColumn("Date", typeof(string)));
        dataTable.Columns.Add(new DataColumn("Type", typeof(string)));
        dataTable.Columns.Add(new DataColumn("Summary", typeof(string)));
        foreach (HealthRecordItem item in items)
        {
            XmlNode mttDocument = item.TransformedXmlData["mtt"].SelectSingleNode("data-xml/row");
            DataRow row         = dataTable.NewRow();
            row["Date"]    = mttDocument.Attributes["wc-date"].Value;
            row["Type"]    = mttDocument.Attributes["wc-type"].Value;
            row["Summary"] = mttDocument.Attributes["summary"].Value;
            dataTable.Rows.Add(row);
        }

        Grid_ReadingsTextSummary.DataSource = dataTable;
        Grid_ReadingsTextSummary.DataBind();
        Grid_ReadingsTextSummary.Visible = true;
    }
        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));
        }
        protected override void ProcessRecord()
        {
            HealthClientApplication clientApp = HvShellUtilities.GetClient();

            List <PersonInfo> authorizedPeople = new List <PersonInfo>(clientApp.ApplicationConnection.GetAuthorizedPeople());

            // Create an authorized connection for each person on the
            //   list.
            HealthClientAuthorizedConnection authConnection = clientApp.CreateAuthorizedConnection(
                authorizedPeople[0].PersonId);

            // Use the authorized connection to read the user's default
            //   health record.
            HealthRecordAccessor access = new HealthRecordAccessor(
                authConnection, authConnection.GetPersonInfo().GetSelfRecord().Id);

            // Search the health record for basic demographic
            //   information.
            //   Most user records contain an item of this type.
            HealthRecordSearcher search = access.CreateSearcher();
            HealthRecordFilter   filter = new HealthRecordFilter(
                HvShellUtilities.NameToTypeId(Type));

            search.Filters.Add(filter);

            foreach (Object o in search.GetMatchingItems()[0])
            {
                WriteObject(o);
            }
        }
        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);
        }
Example #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Lbl_UserName.Text = this.PersonInfo.SelectedRecord.DisplayName;

        HealthRecordSearcher searcher = PersonInfo.SelectedRecord.CreateSearcher();


        HealthRecordFilter filter = new HealthRecordFilter(Weight.TypeId);

        filter.MaxItemsReturned = 10;
        filter.UpdatedDateMin   = DateTime.Now.Subtract(new TimeSpan(365, 0, 0, 0));
        searcher.Filters.Add(filter);

        HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

        Dictionary <string, string> weights = new Dictionary <string, string>();

        foreach (Weight item in items)
        {
            weights[item.When.ToString()] = item.Value.ToString();
        }

        WeightView.DataSource = weights;
        WeightView.DataBind();
    }
Example #10
0
    protected void Btn_ShowWeeklyWeightReadings_Click(object sender, EventArgs e)
    {
        HealthRecordSearcher searcher = PersonInfo.SelectedRecord.CreateSearcher();
        HealthRecordFilter   filter   = new HealthRecordFilter(
            Emotion.TypeId,
            DietaryDailyIntake.TypeId,
            Weight.TypeId,
            SleepJournalAM.TypeId,
            Exercise.TypeId);

        filter.EffectiveDateMin = DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0));
        searcher.Filters.Add(filter);

        HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

        TimeSeries weight         = new TimeSeries("Weight Graph");
        TimeSeries emotions       = new TimeSeries("Emotions");
        TimeSeries dietaryintakes = new TimeSeries("Dietary Intake (Carbs)");
        TimeSeries sleep          = new TimeSeries("Sleep");
        TimeSeries exercise       = new TimeSeries("Exercise");

        foreach (HealthRecordItem item in items)
        {
            if (item is Weight)
            {
                Weight w = (Weight)item;
                weight.SeriesValue.Add(new TimeSeries.TimeSeriesValues(
                                           w.EffectiveDate, w.Value.DisplayValue.Value));
            }
            if (item is Emotion)
            {
                Emotion m = (Emotion)item;
                emotions.SeriesValue.Add(new TimeSeries.TimeSeriesValues(
                                             m.EffectiveDate, 1.0));
            }
            if (item is DietaryDailyIntake)
            {
            }
            if (item is SleepJournalAM)
            {
                SleepJournalAM s = (SleepJournalAM)item;
                sleep.SeriesValue.Add(new TimeSeries.TimeSeriesValues(
                                          s.EffectiveDate, s.SleepMinutes));
            }
            if (item is Exercise)
            {
            }
        }

        TimeplotView.Plots.Add(weight);
        TimeplotView.Plots.Add(emotions);
        TimeplotView.Plots.Add(dietaryintakes);
        TimeplotView.Plots.Add(sleep);
        TimeplotView.Plots.Add(exercise);
        TimeplotView.DataBind();
        TimeplotView.Visible = true;
    }
        private static ReadOnlyCollection <HealthRecordItemCollection> ReadHeight(PersonInfo personInfo)
        {
            HealthRecordSearcher searcher = personInfo.SelectedRecord.CreateSearcher();
            HealthRecordFilter   filter   = new HealthRecordFilter();

            filter.TypeIds.Add(Height.TypeId);
            searcher.Filters.Add(filter);

            ReadOnlyCollection <HealthRecordItemCollection> items = searcher.GetMatchingItems();

            return(items);
        }
        public async Task <IReadOnlyCollection <ThingCollection> > GetThingsAsync(Guid recordId, IEnumerable <ThingQuery> queries)
        {
            Validator.ThrowIfGuidEmpty(recordId, nameof(recordId));

            List <ThingQuery> queriesList = queries.ToList();

            Validator.ThrowIfCollectionNullOrEmpty(queriesList, nameof(queries));

            HealthRecordAccessor accessor = new HealthRecordAccessor(_connection, recordId);
            HealthRecordSearcher searcher = new HealthRecordSearcher(accessor);

            HealthServiceResponseData response = await GetRequestWithParameters(recordId, searcher, queriesList).ConfigureAwait(false);

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

            return(resultSet);
        }
        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));
        }
        private static ReadOnlyCollection <HealthRecordItemCollection> ReadHeight(PersonInfo personInfo)
        {
            HealthRecordSearcher searcher = personInfo.SelectedRecord.CreateSearcher();
            HealthRecordFilter   filter   = new HealthRecordFilter();

            filter.TypeIds.Add(Height.TypeId);
            searcher.Filters.Add(filter);

            //To get blob
            //var item = searcher.GetSingleItem(new Guid("ef21ac67-e525-4a6e-ae5a-e54d3b75c80e"), HealthRecordItemSections.All);
            //var itemBlob = item.GetBlobStore(personInfo.SelectedRecord);
            //foreach(var blob in itemBlob.Values)
            //{
            //    Console.WriteLine(blob.Name);
            //}

            ReadOnlyCollection <HealthRecordItemCollection> items = searcher.GetMatchingItems();

            return(items);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        HealthRecordSearcher searcher = PersonInfo.SelectedRecord.CreateSearcher();

        HealthRecordFilter filter = new HealthRecordFilter(Weight.TypeId);

        searcher.Filters.Add(filter);

        HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

        Dictionary <string, string> weights = new Dictionary <string, string>();

        foreach (Weight item in items)
        {
            weights[item.When.ToString()] = item.Value.ToString();
        }

        WeightView.DataSource = weights;
        WeightView.DataBind();
    }
Example #16
0
        /// <summary>
        /// Creates a connection to HealthVault and obtains weight data
        /// </summary>
        /// <returns></returns>
        public HealthRecordItemCollection GetWeightFromHealthVault()
        {
            if (!_isProvisioned)
            {
                MessageBox.Show("Please provision application first");
                return(null);
            }

            HealthClientAuthorizedConnection connection =
                HealthClientApplication.CreateAuthorizedConnection(PersonId);

            HealthRecordAccessor accessor = new HealthRecordAccessor(connection, RecordId);

            HealthRecordSearcher searcher = accessor.CreateSearcher();
            HealthRecordFilter   filter   = new HealthRecordFilter(ItemTypes.Weight.TypeId);

            searcher.Filters.Add(filter);
            HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

            return(items);
        }
Example #17
0
        public static List <HeightModel> GetValues <T>(Guid typeID, PersonInfo personInfo) where T : HeightModel
        {
            HealthRecordSearcher searcher = personInfo.SelectedRecord.CreateSearcher();

            HealthRecordFilter filter = new HealthRecordFilter(typeID);

            searcher.Filters.Add(filter);

            HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

            List <HeightModel> typedList = new List <HeightModel>();

            foreach (HealthRecordItem item in items)
            {
                Height      itemObj   = (Height)item;
                HeightModel heightObj = new HeightModel(itemObj.Value.Meters, itemObj.When);
                typedList.Add(heightObj);
            }

            return(typedList);
        }
    protected void Btn_ShowWeeklyWeightReadings_Click(object sender, EventArgs e)
    {
        HealthRecordSearcher searcher = PersonInfo.SelectedRecord.CreateSearcher();
        HealthRecordFilter   filter   = new HealthRecordFilter(Weight.TypeId);

        filter.EffectiveDateMin = DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0));
        searcher.Filters.Add(filter);

        HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

        TimeSeries t = new TimeSeries("Weight Graph");

        foreach (Weight item in items)
        {
            //Assuming all data is in one unit
            t.SeriesValue.Add(new TimeSeries.TimeSeriesValues(
                                  item.EffectiveDate, item.Value.DisplayValue.Value));
        }
        TimeplotView.Plots.Add(t);
        TimeplotView.DataBind();
        TimeplotView.Visible = true;
    }
        private async Task <HealthServiceResponseData> GetRequestWithParameters(Guid recordId, HealthRecordSearcher searcher, IEnumerable <ThingQuery> queries)
        {
            foreach (ThingQuery query in queries)
            {
                searcher.Filters.Add(query);
            }

            return(await _connection.ExecuteAsync(HealthVaultMethods.GetThings, 3, GetParametersXml(searcher), recordId, correlationId : CorrelationId).ConfigureAwait(false));
        }
        /// <summary>
        /// Gets the health record items that match the filters as specified by 
        /// the properties of this class.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="searcher">
        /// The searcher that defines what items to return.
        /// </param>
        /// 
        /// <returns>
        /// An XmlReader representing the raw results of the search.
        /// </returns>
        /// 
        /// <remarks>
        /// This method accesses the HealthVault service across the network.
        /// <br/><br/>
        /// This method is typically used when the calling application wants to
        /// handle the raw health record item XML directly instead of using the 
        /// object model.
        /// </remarks>
        /// 
        public virtual XmlReader GetMatchingItemsReader(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            HealthRecordSearcher searcher)
        {
            HealthServiceRequest request = PrepareRequest(connection, accessor, searcher);
            request.Execute();

            return request.Response.InfoReader;
        }
        /// <summary>
        /// Gets the health record items specified by the 
        /// <see cref="HealthRecordSearcher"/> and runs them through the specified 
        /// transform.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="searcher">
        /// The searcher that defines what items to return.
        /// </param>
        /// 
        /// <param name="transform">
        /// A URL to a transform to run on the resulting XML. This can be
        /// a fully-qualified URL or the name of one of the standard XSLs
        /// provided by the HealthVault system.
        /// </param>
        /// 
        /// <returns>
        /// The string resulting from performing the specified transform on
        /// the XML representation of the items.
        /// </returns>
        /// 
        /// <remarks>
        /// This method accesses the HealthVault service across the network.
        /// <br/><br/>
        /// Any call to HealthVault may specify a transform to be run on the
        /// response XML. The transform can be specified as a XSL fragment or
        /// a well-known transform tag provided by the HealthVault service. If a
        /// XSL fragment is specified, it gets compiled and cached on the server.
        /// <br/>
        /// <br/>
        /// A final-xsl is useful when you want to convert the result from XML to
        /// HTML so that you can display the result directly in a web page.
        /// You may also use it to generate other data formats like CCR, CCD, CSV,
        /// RSS, etc.
        /// <br/>
        /// <br/>
        /// Transform fragments cannot contain embedded script. The following set
        /// of parameters are passed to all final-xsl transforms:<br/>
        /// <ul>
        ///     <li>currentDateTimeUtc - the date and time just before the transform 
        ///     started executing</li>
        ///     <li>requestingApplicationName - the name of the application that
        ///     made the request to HealthVault.</li>
        ///     <li>countryCode - the ISO 3166 country code from the request.</li>
        ///     <li>languageCode - the ISO 639-1 language code from the request.</li>
        ///     <li>personName - the name of the person making the request.</li>
        ///     <li>recordName - if the request identified a HealthVault record to 
        ///     be used, this parameter contains the name of that record.</li>
        /// </ul>
        /// </remarks>
        /// 
        /// <exception cref="ArgumentException">
        /// The <paramref name="transform"/> parameter is <b>null</b> or empty.
        /// </exception>
        /// 
        /// <exception cref="ArgumentException">
        /// <see cref="Microsoft.Health.HealthRecordView.Sections"/> does not
        /// contain the XML section in the view.
        /// </exception>
        /// 
        /// <exception cref="HealthServiceException">
        /// There is a failure retrieving the items.
        /// -or-
        /// No filters have been specified.
        /// </exception>
        /// 
        public virtual string GetTransformedItems(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            HealthRecordSearcher searcher,
            string transform)
        {
            Validator.ThrowIfStringNullOrEmpty(transform, "transform");

            HealthServiceRequest request = PrepareRequest(connection, accessor, searcher);

            return request.ExecuteForTransform(transform);
        }
        /// <summary>
        /// Generates the XML for the parameters for the "GetThings" request.
        /// </summary>
        /// 
        /// <returns>
        /// An XML string defining the parameters for the "GetThings" call.
        /// </returns>
        /// 
        /// <exception cref="HealthServiceException">
        /// No filters have been specified.
        /// </exception>
        ///         
        internal static string GetParametersXml(HealthRecordSearcher searcher)
        {
            if (searcher.Filters.Count == 0)
            {
                HealthServiceResponseError error = new HealthServiceResponseError();
                error.Message =
                    ResourceRetriever.GetResourceString(
                        "HealthRecordSearcherNoFilters");

                HealthServiceException e =
                    HealthServiceExceptionHelper.GetHealthServiceException(
                        HealthServiceStatusCode.InvalidFilter, error);
                throw e;

            }

            StringBuilder parameters = new StringBuilder(128);

            XmlWriterSettings settings = SDKHelper.XmlUnicodeWriterSettings;

            using (XmlWriter writer = XmlWriter.Create(parameters, settings))
            {
                foreach (HealthRecordFilter filter in searcher.Filters)
                {
                    // Add all filters
                    filter.AddFilterXml(writer);
                }
                writer.Flush();
            }
            return parameters.ToString();
        }
        /// <summary>
        /// Fills in the data table with data from the HealthVault service
        /// starting at the specific index for the count specified.
        /// </summary>
        ///
        /// <param name="record">
        /// The health record to get the data from.
        /// </param>
        ///
        /// <param name="startIndex">
        /// The index to start retrieving full data from HealthVault.
        /// </param>
        ///
        /// <param name="count">
        /// The count of full items to retrieve.
        /// </param>
        ///
        /// <remarks>
        /// This method makes a web-method call to the HealthVault service.
        ///
        /// The default <see cref="GetData(HealthRecordAccessor)"/> implementation
        /// fills the data with complete information for all items matching
        /// the filter. If the <see cref="ThingDataTable"/> is being
        /// bound to a HealthServiceDataGrid or other such control that supports
        /// paging, this may not be the desired result as many calls to
        /// HealthVault may be required to fetch all the data.  This overload
        /// of GetData allows the caller to specify the index and the count of
        /// the full items to retrieve to match the page that is currently visible.
        /// The <see cref="ThingDataTable"/> will be filled with
        /// empty values except for the rows specified.
        /// </remarks>
        ///
        /// <exception cref="HealthServiceException">
        /// An error occurred while accessing the HealthVault service.
        /// </exception>
        ///
        public async Task GetData(
            HealthRecordAccessor record,
            int startIndex,
            int count)
        {
            ThingDataTableView effectiveView =
                await this.ApplyEffectiveViewAsync(record.Connection).ConfigureAwait(false);

            // Need to specify the type version to ensure that the columns match when the app
            // supports multiple versions.
            if (effectiveView == ThingDataTableView.SingleTypeTable)
            {
                for (int index = 0; index < this.Query.TypeIds.Count; ++index)
                {
                    this.Query.View.TypeVersionFormat.Add(this.Query.TypeIds[index]);
                }
            }

            HealthRecordSearcher searcher = record.CreateSearcher();

            searcher.Filters.Add(this.Query);

            XPathNavigator nav = await searcher.GetMatchingItemsRaw().ConfigureAwait(false);

            _hasData = true;

            XPathNavigator navFiltered =
                nav.SelectSingleNode("//group/filtered");

            if (navFiltered != null)
            {
                _wasFiltered = navFiltered.ValueAsBoolean;
            }

            int numberOfFullThingsToRetrieve = AddRows(nav);

            List <ThingKey> partialThingKeys =
                GetPartialThingKeys(nav);

            int thingIndex = numberOfFullThingsToRetrieve;
            int partialThingsCurrentIndex = 0;

            while (thingIndex < startIndex &&
                   partialThingsCurrentIndex < partialThingKeys.Count)
            {
                AddPartialThingRow(partialThingKeys[partialThingsCurrentIndex++]);
                ++thingIndex;
            }

            while (thingIndex < startIndex + count &&
                   partialThingsCurrentIndex < partialThingKeys.Count)
            {
                nav =
                    await GetPartialThings(
                        record,
                        partialThingKeys,
                        partialThingsCurrentIndex,
                        numberOfFullThingsToRetrieve).ConfigureAwait(false);

                // Note, not all partial things may still exist when doing
                // the next query so AddRows may return less than
                // numberOfFullThingsToRetrieve. Just skip anything that is
                // missing.
                AddRows(nav);

                partialThingsCurrentIndex += numberOfFullThingsToRetrieve;
                thingIndex += numberOfFullThingsToRetrieve;
            }

            while (partialThingsCurrentIndex < partialThingKeys.Count)
            {
                AddPartialThingRow(partialThingKeys[partialThingsCurrentIndex++]);
                ++thingIndex;
            }
        }
        /// <summary>
        /// Checks whether at least one filter was specified
        /// and that all specified filters are valid.
        /// </summary>
        /// 
        /// <exception cref="HealthServiceResponseError">
        /// If no filter was specified or if any specified filter was invalid.
        /// </exception>
        /// 
        internal static void ValidateFilters(HealthRecordSearcher searcher)
        {
            if (searcher.Filters.Count == 0)
            {
                HealthServiceResponseError error = new HealthServiceResponseError();

                error.Message =
                    ResourceRetriever.GetResourceString(
                        "HealthRecordSearcherInvalidFilter");

                HealthServiceException e =
                    HealthServiceExceptionHelper.GetHealthServiceException(
                        HealthServiceStatusCode.InvalidFilter,
                        error);
                throw e;
            }

            for (int i = 0; i < searcher.Filters.Count; ++i)
            {
                searcher.Filters[i].ThrowIfNotValid();
            }
        }
        /// <summary>
        /// Executes the search using the filters supplied.
        /// </summary>
        /// 
        /// <exception cref="HealthServiceException">
        /// The response from the server was anything but 
        /// HealthServiceStatusCode.OK, or no filters have been specified.
        /// </exception>
        ///         
        private static ReadOnlyCollection<HealthRecordItemCollection> Execute(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            HealthRecordSearcher searcher)
        {
            HealthServiceRequest request = PrepareRequest(connection, accessor, searcher);

            request.Execute();

            XmlReader infoReader = request.Response.InfoReader;

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

            if ((infoReader != null) && (infoReader.ReadToDescendant("group")))
            {
                while (infoReader.Name == "group")
                {
                    XmlReader groupReader = infoReader.ReadSubtree();

                    groupReader.MoveToContent();

                    HealthRecordItemCollection resultGroup =
                        HealthRecordItemCollection.CreateResultGroupFromResponse(
                            accessor,
                            groupReader,
                            searcher.Filters);

                    groupReader.Close();

                    // infoReader will normally be at the end element of
                    // the group at this point, and needs a read to get to
                    // the next element. If the group was empty, infoReader
                    // will be at the beginning of the group, and a
                    // single read will still move to the next element.
                    infoReader.Read();
                    if (resultGroup != null)
                    {
                        result.Add(resultGroup);
                    }
                }
            }

            return new ReadOnlyCollection<HealthRecordItemCollection>(result);
        }
Example #26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Lbl_UserName.Text = this.PersonInfo.SelectedRecord.DisplayName;

        HealthRecordSearcher searcher = PersonInfo.SelectedRecord.CreateSearcher();
        HealthRecordFilter   filter   = new HealthRecordFilter(
            ApplicationSpecific.TypeId,
            Emotion.TypeId,
            DietaryDailyIntake.TypeId,
            Weight.TypeId,
            SleepJournalAM.TypeId,
            Exercise.TypeId);

        filter.EffectiveDateMin = DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0));
        searcher.Filters.Add(filter);

        HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

        List <Weight>              weights          = new List <Weight>();
        List <Emotion>             emotions         = new List <Emotion>();
        List <SleepJournalAM>      sleep            = new List <SleepJournalAM>();
        List <DietaryDailyIntake>  dietaryintake    = new List <DietaryDailyIntake>();
        List <Exercise>            exercise         = new List <Exercise>();
        List <ApplicationSpecific> selfexperiements = new List <ApplicationSpecific>();

        foreach (HealthRecordItem item in items)
        {
            if (item is Weight)
            {
                weights.Add((Weight)item);
            }
            if (item is Emotion)
            {
                emotions.Add((Emotion)item);
            }
            if (item is DietaryDailyIntake)
            {
                dietaryintake.Add((DietaryDailyIntake)item);
            }
            if (item is SleepJournalAM)
            {
                sleep.Add((SleepJournalAM)item);
            }
            if (item is Exercise)
            {
                exercise.Add((Exercise)item);
            }
            if (item is ApplicationSpecific)
            {
                selfexperiements.Add((ApplicationSpecific)item);
            }
        }


        DisplayWeight(weights);
        DisplayMood(emotions);
        DisplayDailyDiet(dietaryintake);
        DisplaySleep(sleep);
        DisplayExercise(exercise);
        DisplaySelfExperiments(selfexperiements);
        DataBindMoodInputControls();
    }
        /// <summary>
        /// Gets the request object including the necessary parameters for
        /// the "GetThings" request.
        /// </summary>
        /// 
        /// <returns>
        /// The request object for the thing search with the parameters filled
        /// in.
        /// </returns>
        /// 
        /// <exception cref="HealthServiceException">
        /// No filters have been specified.
        /// </exception>
        ///         
        private static HealthServiceRequest PrepareRequest(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            HealthRecordSearcher searcher)
        {
            HealthServiceRequest request =
                new HealthServiceRequest(connection, "GetThings", 3, accessor);

            request.Parameters = GetParametersXml(searcher);
            return request;
        }
        /// <summary>
        /// Creates a new open query using the specified 
        /// connection, definition, expiration time,
        /// personal identification number (PIN), description, and XSL.
        /// </summary>
        /// 
        /// <param name="connection">
        /// A <see cref="ApplicationConnection"/> instance that creates the 
        /// new open query.
        /// </param>
        /// 
        /// <param name="searcher">
        /// A <see cref="HealthRecordSearcher"/> instance that defines the open query.
        /// </param>
        ///
        /// <param name="expires">
        /// The number of minutes the query will expire from the creation time.
        /// A value of Int32.MaxValue denotes that the query does not expire.
        /// </param>
        ///
        /// <param name="pinCode">
        /// The PIN that protects the query.  
        /// </param>
        ///
        /// <param name="note">
        /// The note describing the query.
        /// </param>
        /// 
        /// <param name="finalXsl">
        /// The XSL that transforms the results of the query when the 
        /// <see cref="OpenQuery"/> is invoked.
        /// </param>
        /// 
        /// <returns>
        /// An <see cref="OpenQuery"/> instance that represents the newly created query.
        /// </returns>
        /// 
        /// <remarks>
        /// The creation of an open query makes public the data returned by that 
        /// query. However, the query URL must be known to retrieve the data.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="connection"/> or <paramref name="searcher"/> 
        /// parameter is <b>null</b>.
        /// </exception>
        /// 
        /// 
        /// <exception cref="ArgumentException">
        /// The <paramref name="searcher"/> parameter contains no valid search
        /// filters or the <paramref name="pinCode"/> parameter is <b>null</b> 
        /// or empty.
        /// </exception>
        /// 
        /// <exception cref="HealthServiceException">
        /// An error occurred when HealthVault processed the request.
        /// </exception>
        /// 
        public virtual OpenQuery NewOpenQuery(
            ApplicationConnection connection,
            HealthRecordSearcher searcher,
            int expires,
            string pinCode,
            string note,
            string finalXsl)
        {
            Validator.ThrowIfArgumentNull(connection, "connection", "NewQueryNullService");
            Validator.ThrowIfArgumentNull(searcher, "searcher", "NewQueryNullSearcher");

            Validator.ThrowArgumentExceptionIf(
                searcher.Filters == null ||
                searcher.Filters.Count == 0,
                "searcher.Filters",
                "NewQuerySearcherNoFilters");

            HealthServiceRequest request =
                new HealthServiceRequest(connection, "SaveOpenQuery", 1, searcher.Record);

            request.Parameters =
                GetSaveOpenQueryParameters(
                    searcher,
                    expires,
                    pinCode,
                    note,
                    finalXsl);
            request.Execute();

            return
                CreateOpenQueryFromSaveOpenQueryResponse(
                    request.Response.InfoNavigator);
        }
        /// <summary>
        /// Gets the health record items that match the filters as specified by 
        /// the properties of this class.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="searcher">
        /// The searcher that defines what items to return.
        /// </param>
        /// 
        /// <returns>
        /// A collection of health record items that match the applied filters.
        /// </returns>
        /// 
        /// <remarks>
        /// This method accesses the HealthVault service across the network.
        /// </remarks>
        /// 
        /// <exception cref="HealthServiceException">
        /// The response from the server was anything but 
        /// <see cref="HealthServiceStatusCode.Ok"/>.
        /// -or-
        /// <see cref="Microsoft.Health.HealthRecordSearcher.Filters"/> is empty
        /// or contains invalid filters.
        /// </exception>
        /// 
        public virtual ReadOnlyCollection<HealthRecordItemCollection> GetMatchingItems(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            HealthRecordSearcher searcher)
        {
            ValidateFilters(searcher);

            return Execute(connection, accessor, searcher);
        }
        private static string GetSaveOpenQueryParameters(
            HealthRecordSearcher searcher,
            int expires,
            string pinCode,
            string note,
            string finalXsl)
        {
            string searcherParameters = searcher.GetParametersXml();

            return GetSaveOpenQueryParameters(
                "GetThings",
                "3",
                searcher.Record.Id,
                expires,
                pinCode,
                note,
                finalXsl,
                searcherParameters);
        }