Ejemplo n.º 1
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));
        }
Ejemplo n.º 2
0
        public void DeProvision()
        {
            Guid tempPersonId = _personId;
            Guid tempRecordId = _recordId;

            // first reset local state so
            // that even if things fail after this
            // the next app launch will have fresh state
            _isProvisioned = false;
            _personId      = Guid.Empty;
            _recordId      = Guid.Empty;
            _applicationId = Guid.Empty;
            SaveUserSettings();

            // attempt to remove authorization of application from server
            HealthClientAuthorizedConnection connection =
                HealthClientApplication.CreateAuthorizedConnection(tempPersonId);

            HealthRecordAccessor accessor = new HealthRecordAccessor(connection, tempRecordId);

            accessor.RemoveApplicationAuthorization();

            // delete the local certificate
            _healthClientApplication.DeleteCertificate();

            _healthClientApplication = null;
        }
Ejemplo n.º 3
0
        public void RevokeApplicationConnection(Guid recordId)
        {
            // connection must have been created in the context of a person
            HealthRecordAccessor record = new HealthRecordAccessor(_connection, recordId);

            record.RemoveApplicationAuthorization();
        }
        public static void PutThings(OfflineWebApplicationConnection connection, Guid recordId, ref HealthRecordItem newItem)
        {
            HealthRecordAccessor record = new HealthRecordAccessor(connection, recordId);

            record.NewItem(newItem);
            return;
        }
Ejemplo n.º 5
0
        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);
            }
        }
        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>
        /// Gets the permissions which the authenticated person
        /// has when using the calling application for the specified item types
        /// in this  record.
        /// </summary>
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// <param name="healthRecordItemTypeIds">
        /// A collection of unique identifiers to identify the health record
        /// item types, for which the permissions are being queried.
        /// </param>
        /// <returns>
        /// Returns a dictionary of <see cref="ThingTypePermission"/>
        /// with thing types as the keys.
        /// </returns>
        ///
        /// <remarks>
        /// If the list of thing types is empty, an empty dictionary is
        /// returned. If for a thing type, the person has
        /// neither online access nor offline access permissions,
        /// <b> null </b> will be returned for that type in the dictionary.
        /// </remarks>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="healthRecordItemTypeIds"/> is <b>null</b>.
        /// </exception>
        ///
        /// <exception cref="HealthServiceException">
        /// If there is an exception during executing the request to HealthVault.
        /// </exception>
        ///
        public virtual async Task <IDictionary <Guid, ThingTypePermission> > QueryPermissionsByTypesAsync(
            IHealthVaultConnection connection,
            HealthRecordAccessor accessor,
            IList <Guid> healthRecordItemTypeIds)
        {
            HealthRecordPermissions recordPermissions = await QueryRecordPermissionsAsync(connection, accessor, healthRecordItemTypeIds).ConfigureAwait(false);

            Collection <ThingTypePermission> typePermissions = recordPermissions.ItemTypePermissions;

            Dictionary <Guid, ThingTypePermission> permissions = new Dictionary <Guid, ThingTypePermission>();

            foreach (Guid typeId in healthRecordItemTypeIds)
            {
                if (!permissions.ContainsKey(typeId))
                {
                    permissions.Add(typeId, null);
                }
            }

            foreach (ThingTypePermission typePermission in typePermissions)
            {
                permissions[typePermission.TypeId] = typePermission;
            }

            return(permissions);
        }
Ejemplo n.º 8
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));
        }
        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);
        }
Ejemplo n.º 10
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);
        }
        /// <summary>
        /// Fills in the data table with data from a list of ThingBase.
        /// </summary>
        /// <param name="record"/>
        /// <param name="items"/>
        /// <param name="startIndex"/>
        /// <param name="count"/>
        public async Task GetDataAsync(HealthRecordAccessor record, IList <ThingBase> items, int startIndex, int count)
        {
            ThingDataTableView effectiveView =
                await this.ApplyEffectiveViewAsync(record.Connection).ConfigureAwait(false);

            IDictionary <Guid, ThingTypeDefinition> typeDefDict =
                await ItemTypeManager.GetHealthRecordItemTypeDefinitionAsync(query.TypeIds,
                                                                             record.Connection).ConfigureAwait(false);

            ThingTypeDefinition sttTypeDef =
                typeDefDict.Count == 1 ? typeDefDict[query.TypeIds[0]] : null;

            bool   firstRow      = true;
            string transformName =
                (effectiveView == ThingDataTableView.SingleTypeTable) ? "stt" : "mtt";

            for (int i = startIndex; i < items.Count && i < count; ++i)
            {
                ThingBase item = items[i];

                XPathNavigator itemTransformNav;
                IDictionary <string, XDocument> transformedXmlData = item.TransformedXmlData;
                if (transformedXmlData.ContainsKey(transformName))
                {
                    itemTransformNav =
                        transformedXmlData[transformName].CreateNavigator().SelectSingleNode(
                            "//data-xml/row");
                }
                else
                {
                    string transform = (sttTypeDef == null) ?
                                       ThingTypeDefinitionHelper.Create(typeDefDict[item.TypeId]).TransformItem(transformName, item) :
                                       ThingTypeDefinitionHelper.Create(sttTypeDef).TransformItem(transformName, item);

                    XmlReaderSettings settings = new XmlReaderSettings()
                    {
                        XmlResolver   = null,
                        DtdProcessing = DtdProcessing.Prohibit
                    };

                    using (StringReader stringReader = new StringReader(transform))
                    {
                        itemTransformNav = new XPathDocument(XmlReader.Create(stringReader, settings)).CreateNavigator();
                    }

                    if (!itemTransformNav.MoveToFirstChild())
                    {
                        continue;
                    }
                }

                if (firstRow)
                {
                    SetupColumns(itemTransformNav.Clone());
                    firstRow = false;
                }
                AddRow(itemTransformNav);
            }
        }
        /// <summary>
        /// Gets the permissions which the authenticated person
        /// has when using the calling application for the specified item types
        /// in this health record.
        /// </summary>
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// <param name="healthRecordItemTypeIds">
        /// A collection of uniqueidentifiers to identify the health record
        /// item types, for which the permissions are being queried.
        /// </param>
        /// <returns>
        /// A list of <see cref="ThingTypePermission"/>
        /// objects which represent the permissions that the current
        /// authenticated person has for the HealthRecordItemTypes specified
        /// in the current health record when using the current application.
        /// </returns>
        ///
        /// <remarks>
        /// If the list of thing types is empty, an empty list is
        /// returned. If for a thing type, the person has
        /// neither online access nor offline access permissions,
        /// ThingTypePermission object is not returned for that
        /// thing type.
        /// </remarks>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="healthRecordItemTypeIds"/> is <b>null</b>.
        /// </exception>
        ///
        /// <exception cref="HealthServiceException">
        /// If there is an exception during executing the request to HealthVault.
        /// </exception>
        ///
        public virtual async Task <Collection <ThingTypePermission> > QueryPermissionsAsync(
            IHealthVaultConnection connection,
            HealthRecordAccessor accessor,
            IList <Guid> healthRecordItemTypeIds)
        {
            HealthRecordPermissions permissions = await QueryRecordPermissionsAsync(connection, accessor, healthRecordItemTypeIds).ConfigureAwait(false);

            return(permissions.ItemTypePermissions);
        }
        /// <summary>
        /// Fills in the data table with data from the HealthVault service.
        /// </summary>
        ///
        /// <param name="recordId">
        /// The unique health record identifier to get the data from.
        /// </param>
        ///
        /// <param name="connection">
        /// The connection to the HealthVault service to use.
        /// </param>
        ///
        /// <remarks>
        /// This method makes a web-method call to the HealthVault service.
        /// </remarks>
        ///
        /// <exception cref="HealthServiceException">
        /// An error occurred while accessing the HealthVault service.
        /// </exception>
        ///
        public async Task GetData(
            Guid recordId,
            IConnectionInternal connection)
        {
            HealthRecordAccessor record =
                new HealthRecordAccessor(connection, recordId);

            await GetDataAsync(record).ConfigureAwait(false);
        }
        private const int DefaultStreamBufferSize = 1 << 20; // 1MB

        /// <summary>
        /// Constructs an instance of the Blob class with the specified values.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the BLOB. It can be <see cref="string.Empty"/> but cannot be <b>null</b>.
        /// </param>
        ///
        /// <param name="contentType">
        /// The content type of the BLOB.
        /// </param>
        ///
        /// <param name="currentContentEncoding">
        /// The current content encoding of the BLOB or <b>null</b> if the BLOB is not encoded.
        /// </param>
        ///
        /// <param name="legacyContentEncoding">
        /// The previous content encoding of the BLOB (if any).
        /// </param>
        ///
        /// <param name="record">
        /// The health record to write the BLOB data to.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="name"/> or <paramref name="contentType"/> is <b>null</b>.
        /// </exception>
        ///
        internal Blob(
            string name,
            string contentType,
            string currentContentEncoding,
            string legacyContentEncoding,
            HealthRecordAccessor record)
            : this(name, contentType, currentContentEncoding, legacyContentEncoding, null, record)
        {
        }
Ejemplo n.º 15
0
        public static void PostThing(HealthRecordItem thing, Guid personId, Guid recordId)
        {
            Guid appId = new Guid(Connections.ApplicationId);
            OfflineWebApplicationConnection connection = Connections.CreateConnection(appId, personId);

            HealthRecordAccessor accessor = new HealthRecordAccessor(connection, recordId);

            accessor.NewItem(thing);
        }
Ejemplo n.º 16
0
        private static List <T> GetValues <T>(Guid typeId, HealthRecordAccessor access) where T : HealthRecordItem
        {
            var searcher = access.CreateSearcher();

            var filter = new HealthRecordFilter(typeId);

            searcher.Filters.Add(filter);

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

            return(items.Cast <T>().ToList());
        }
Ejemplo n.º 17
0
        public static void PurgeCustomData(Guid personId, Guid recordId)
        {
            Guid appId = new Guid(Connections.ApplicationId);
            OfflineWebApplicationConnection connection = Connections.CreateConnection(appId, personId);

            HealthRecordAccessor accessor = new HealthRecordAccessor(connection, recordId);

            foreach (ApplicationSpecific item in accessor.GetItemsByType(ApplicationSpecific.TypeId))
            {
                accessor.RemoveItem(item);
            }
        }
        public void InitializeTest()
        {
            Ioc.Container = new DependencyInjectionContainer();

            IConnectionInternal connection = Substitute.For <IConnectionInternal>();

            _healthRecordAccessor = Substitute.For <HealthRecordAccessor>();

            _thingTypeRegistrar = new ThingTypeRegistrar();
            _thingDeserializer  = new ThingDeserializer(connection, _thingTypeRegistrar);

            Ioc.Container.Configure(c => c.ExportInstance(_thingTypeRegistrar).As <IThingTypeRegistrar>());
        }
Ejemplo n.º 19
0
        public void SetTemperatureOnHealthVault(double tempValue)
        {
            try
            {
                if (!_isProvisioned)
                {
                    MessageBox.Show("Please provision application first");
                    return;
                }

                HealthClientAuthorizedConnection connection =
                    HealthClientApplication.CreateAuthorizedConnection(PersonId);

                HealthRecordAccessor accessor = new HealthRecordAccessor(connection, RecordId);


                TemperatureMeasurement temperature = new TemperatureMeasurement(tempValue);

                VitalSigns vitalSign = new VitalSigns();

                //generate random date
                DateTime startDate = new DateTime(2018, 1, 1);
                DateTime endDate   = new DateTime(2018, 12, 30);

                TimeSpan timeSpan   = endDate - startDate;
                var      randomTest = new Random();
                TimeSpan newSpan    = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
                DateTime newDate    = startDate + newSpan;


                //set time now
                //vitalSign.When = new HealthServiceDateTime(DateTime.UtcNow);

                vitalSign.When = new HealthServiceDateTime(newDate);

                CodableValue codableValue = new CodableValue();
                codableValue.Text = "celsius";

                VitalSignsResultType vitalSignsResultType = new VitalSignsResultType();
                vitalSignsResultType.Unit       = codableValue;
                vitalSignsResultType.TextValue  = "Temperature";
                vitalSignsResultType.Title.Text = "Temperature";
                vitalSignsResultType.Value      = tempValue;
                vitalSign.VitalSignsResults.Add(vitalSignsResultType);
                accessor.NewItem(vitalSign);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// Gets valid group memberships for a record.
        /// </summary>
        ///
        /// <remarks>
        /// Group membership thing types allow an application to signify that the
        /// record belongs to an application defined group.  A record in the group may be
        /// eligible for special programs offered by other applications, for example.
        /// Applications then need a away to query for valid group memberships.
        /// <br/>
        /// Valid group memberships are those memberships which are not expired, and whose
        /// last updating application is authorized by the last updating person to
        /// read and delete the membership.
        /// </remarks>
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// <param name="applicationIds">
        /// A collection of unique application identifiers for which to
        /// search for group memberships.  For a null or empty application identifier
        /// list, return all valid group memberships for the record.  Otherwise,
        /// return only those group memberships last updated by one of the
        /// supplied application identifiers.
        /// </param>
        /// <returns>
        /// A List of things representing the valid group memberships.
        /// </returns>
        /// <exception cref="HealthServiceException">
        /// If an error occurs while contacting the HealthVault service.
        /// </exception>
        public virtual async Task <Collection <ThingBase> > GetValidGroupMembershipAsync(
            IHealthVaultConnection connection,
            HealthRecordAccessor accessor,
            IList <Guid> applicationIds)
        {
            StringBuilder parameters = new StringBuilder(128);

            if (applicationIds != null)
            {
                XmlWriterSettings settings = SDKHelper.XmlUnicodeWriterSettings;
                using (XmlWriter writer = XmlWriter.Create(parameters, settings))
                {
                    foreach (Guid guid in applicationIds)
                    {
                        writer.WriteElementString(
                            "application-id",
                            guid.ToString());
                    }
                }
            }

            var thingDeserializer = Ioc.Container.Locate <IThingDeserializer>(
                new
            {
                connection         = connection,
                thingTypeRegistrar = Ioc.Get <IThingTypeRegistrar>()
            });

            HealthServiceResponseData responseData = await connection.ExecuteAsync(HealthVaultMethods.GetValidGroupMembership, 1, parameters.ToString()).ConfigureAwait(false);

            XPathExpression infoPath =
                SDKHelper.GetInfoXPathExpressionForMethod(
                    responseData.InfoNavigator,
                    "GetValidGroupMembership");

            XPathNavigator infoNav = responseData.InfoNavigator.SelectSingleNode(infoPath);

            Collection <ThingBase> memberships = new Collection <ThingBase>();

            XPathNodeIterator membershipIterator = infoNav.Select("thing");

            if (membershipIterator != null)
            {
                foreach (XPathNavigator membershipNav in membershipIterator)
                {
                    memberships.Add(thingDeserializer.Deserialize(membershipNav.OuterXml));
                }
            }

            return(memberships);
        }
Ejemplo n.º 21
0
        private static T GetSingleValue <T>(Guid typeId, HealthRecordAccessor access) where T : class
        {
            var searcher = access.CreateSearcher();

            var filter = new HealthRecordFilter(typeId);

            searcher.Filters.Add(filter);

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

            if (items != null && items.Count > 0)
            {
                return(items[0] as T);
            }
            return(null);
        }
        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);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a connection to HealthVault and sets weight data
        /// </summary>
        /// <param name="weightValue"></param>
        public void SetWeightOnHealthVault(double weightValue)
        {
            if (!_isProvisioned)
            {
                MessageBox.Show("Please provision application first");
                return;
            }

            HealthClientAuthorizedConnection connection =
                HealthClientApplication.CreateAuthorizedConnection(PersonId);

            HealthRecordAccessor accessor = new HealthRecordAccessor(connection, RecordId);

            ItemTypes.Weight weight = new ItemTypes.Weight();
            weight.Value = new WeightValue(weightValue);
            accessor.NewItem(weight);
        }
        /// <summary>
        /// Constructs an instance of the Blob class with the specified values.
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the BLOB. It can be <see cref="string.Empty"/> but cannot be <b>null</b>.
        /// </param>
        ///
        /// <param name="contentType">
        /// The content type of the BLOB.
        /// </param>
        ///
        /// <param name="currentContentEncoding">
        /// The current content encoding of the BLOB or <b>null</b> if the BLOB is not encoded.
        /// </param>
        ///
        /// <param name="legacyContentEncoding">
        /// The previous content encoding of the BLOB (if any).
        /// </param>
        ///
        /// <param name="hashInfo">
        /// The hash information for the BLOB.
        /// </param>
        ///
        /// <param name="record">
        /// The health record to write the BLOB data to.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="name"/> or <paramref name="contentType"/> is <b>null</b>.
        /// </exception>
        ///
        internal Blob(
            string name,
            string contentType,
            string currentContentEncoding,
            string legacyContentEncoding,
            BlobHashInfo hashInfo,
            HealthRecordAccessor record)
        {
            Validator.ThrowIfArgumentNull(name, nameof(name), Resources.StringNull);
            Validator.ThrowIfArgumentNull(contentType, nameof(contentType), Resources.StringNull);

            Name                  = name;
            ContentType           = contentType;
            ContentEncoding       = currentContentEncoding;
            LegacyContentEncoding = legacyContentEncoding;
            HashInfo              = hashInfo;
            _record               = record;
        }
        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));
        }
Ejemplo n.º 26
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);
        }
        /// <summary>
        /// Gets the permissions which the authenticated person
        /// has when using the calling application for the specified item types
        /// in this health record as well as the other permission settings such as MeaningfulUseOptIn.
        /// </summary>
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// <param name="healthRecordItemTypeIds">
        /// A collection of uniqueidentifiers to identify the health record
        /// item types, for which the permissions are being queried.
        /// </param>
        /// <returns>
        /// A <see cref="HealthRecordPermissions"/> object
        /// which contains a collection of <see cref="ThingTypePermission"/> objects and
        /// other permission settings.
        /// </returns>
        ///
        /// <remarks>
        /// If the list of thing types is empty, an empty list is
        /// returned for <see cref="HealthRecordPermissions"/> object's ItemTypePermissions property.
        /// If for a thing type, the person has
        /// neither online access nor offline access permissions,
        /// ThingTypePermission object is not returned for that
        /// thing type.
        /// </remarks>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="healthRecordItemTypeIds"/> is <b>null</b>.
        /// </exception>
        ///
        /// <exception cref="HealthServiceException">
        /// There is an error in the server request.
        /// </exception>
        ///
        public virtual async Task <HealthRecordPermissions> QueryRecordPermissionsAsync(
            IHealthVaultConnection connection,
            HealthRecordAccessor accessor,
            IList <Guid> healthRecordItemTypeIds)
        {
            Validator.ThrowIfArgumentNull(healthRecordItemTypeIds, nameof(healthRecordItemTypeIds), Resources.CtorhealthRecordItemTypeIdsArgumentNull);

            string parameters = GetQueryPermissionsParametersXml(healthRecordItemTypeIds);

            HealthServiceResponseData responseData = await connection.ExecuteAsync(HealthVaultMethods.QueryPermissions, 1, parameters).ConfigureAwait(false);

            XPathNavigator infoNav =
                responseData.InfoNavigator.SelectSingleNode(
                    GetQueryPermissionsInfoXPathExpression(
                        responseData.InfoNavigator));

            HealthRecordPermissions recordPermissions         = new HealthRecordPermissions();
            XPathNodeIterator       thingTypePermissionsNodes =
                infoNav.Select("thing-type-permission");

            foreach (XPathNavigator nav in thingTypePermissionsNodes)
            {
                ThingTypePermission thingTypePermissions =
                    ThingTypePermission.CreateFromXml(nav);
                recordPermissions.ItemTypePermissions.Add(thingTypePermissions);
            }

            XPathNavigator valueNav = infoNav.SelectSingleNode("other-settings/meaningfuluse-opt-in");

            if (valueNav != null)
            {
                recordPermissions.MeaningfulUseOptIn = valueNav.ValueAsBoolean;
            }
            else
            {
                recordPermissions.MeaningfulUseOptIn = null;
            }

            return(recordPermissions);
        }
Ejemplo n.º 28
0
        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);

            Weight weight = new Weight();

            weight.Value = new WeightValue(Value / 2.2,
                                           new DisplayValue(Value, "pounds"));

            access.NewItem(weight);
        }
Ejemplo n.º 29
0
        private void ContributeCCDAViaRecordAuthorization()
        {
            // Note: Applications can store the HealthVault personID and recordID and use this to make offline requests to store new information
            // in the patient's record whenever new data is available. In this sample, since we don't maintain offline storage (i.e. a DB) to associate
            // the data source organization's patient identifier with the HealthVault person and record ID, we instead sign-in the user to determine the
            // person and record ID everytime a request to send a new CCDA to HealthVault happens (i.e. clicking the "Send CCDA to HealthVault" button);

            PersonInfo pi = WebApplicationUtilities.LoadPersonInfoFromCookie(HttpContext.Current);

            if (pi == null)
            {
                OutputMessage(lblErrorOutput, "Must login first");
                return;
            }

            // Make the offline call to stor the CCDA in the patient's HealthVault record.
            OfflineWebApplicationConnection connection      = new OfflineWebApplicationConnection(pi.PersonId);
            HealthRecordAccessor            receordAccessor = new HealthRecordAccessor(connection, pi.SelectedRecord.Id);

            receordAccessor.NewItem(_newCcdaItem);

            OutputMessage(lblSuccessOutput, "Successfully sent CCDA document to HealthVault via Record Authorization.");
        }
Ejemplo n.º 30
0
        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 accessor = new HealthRecordAccessor(
                authConnection, authConnection.GetPersonInfo().GetSelfRecord().Id);

            HealthServiceRequest request =
                new HealthServiceRequest(accessor.Connection, "PutThings", 2, accessor);

            // Read the input file
            request.Parameters = System.IO.File.ReadAllText(Path.GetFullPath(FileName));
            request.Execute();
        }
        /// <summary>
        /// Creates new health record items associated with the record.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="items">
        /// The health record items from which to create new instances.
        /// </param>
        /// 
        /// <remarks>
        /// This method accesses the HealthVault service across the network.
        /// </remarks>
        /// 
        /// <exception cref="HealthServiceException">
        /// The HealthVault service returned an error. 
        /// The exception's Error property will contain the index of the
        /// item on which the failure occurred in the ErrorInfo property. If any failures occur, 
        /// no items will have been created.
        /// </exception>
        /// 
        /// <exception cref="ArgumentNullException">
        /// At least one HealthRecordItem in the supplied list was null.
        /// </exception>
        /// 
        public virtual void NewItems(
            ApplicationConnection connection,
            HealthRecordAccessor accessor, 
            IList<HealthRecordItem> items)
        {
            Validator.ThrowIfArgumentNull(items, "items", "NewItemsNullItem");

            HealthServiceRequest request =
                new HealthServiceRequest(connection, "PutThings", 2, accessor);

            StringBuilder infoXml = new StringBuilder();
            XmlWriterSettings settings = SDKHelper.XmlUnicodeWriterSettings;

            using (XmlWriter infoXmlWriter =
                XmlWriter.Create(infoXml, settings))
            {
                foreach (HealthRecordItem item in items)
                {
                    Validator.ThrowIfArgumentNull(item, "items", "NewItemsNullItem");

                    item.WriteItemXml(infoXmlWriter);
                }
                infoXmlWriter.Flush();
            }

            // Add the XML to the request.
            request.Parameters = infoXml.ToString();

            // Call the web-service
            request.Execute();

            // Now update the Id for the new item
            XPathNodeIterator thingIds =
                request.Response.InfoNavigator.Select(
                    GetThingIdXPathExpression(request.Response.InfoNavigator));

            int thingIndex = 0;
            foreach (XPathNavigator thingIdNav in thingIds)
            {
                if (items[thingIndex] != null)
                {
                    items[thingIndex].Key =
                        new HealthRecordItemKey(
                            new Guid(thingIdNav.Value),
                            new Guid(thingIdNav.GetAttribute(
                                    "version-stamp", String.Empty)));
                }
                thingIndex++;
            }
        }
        /// <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);
        }
        /// <summary>
        /// Gets the permissions which the authenticated person 
        /// has when using the calling application for the specified item types
        /// in this  record.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        ///
        /// <param name="healthRecordItemTypeIds">
        /// A collection of unique identifiers to identify the health record  
        /// item types, for which the permissions are being queried. 
        /// </param>
        /// 
        /// <returns>
        /// Returns a dictionary of <see cref="HealthRecordItemTypePermission"/> 
        /// with health record item types as the keys. 
        /// </returns>
        /// 
        /// <remarks> 
        /// If the list of health record item types is empty, an empty dictionary is 
        /// returned. If for a health record item type, the person has 
        /// neither online access nor offline access permissions, 
        /// <b> null </b> will be returned for that type in the dictionary.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="healthRecordItemTypeIds"/> is <b>null</b>.
        /// </exception>
        /// 
        /// <exception cref="HealthServiceException">
        /// If there is an exception during executing the request to HealthVault. 
        /// </exception>
        /// 
        public virtual IDictionary<Guid, HealthRecordItemTypePermission> QueryPermissionsByTypes(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            IList<Guid> healthRecordItemTypeIds)
        {
            Validator.ThrowIfArgumentNull(healthRecordItemTypeIds, "healthRecordItemTypeIds", "CtorhealthRecordItemTypeIdsArgumentNull");

            Dictionary<Guid, HealthRecordItemTypePermission> permissions =
                new Dictionary<Guid, HealthRecordItemTypePermission>();

            HealthServiceRequest request =
                new HealthServiceRequest(connection, "QueryPermissions", 1, accessor);

            for (int i = 0; i < healthRecordItemTypeIds.Count; ++i)
            {
                if (!permissions.ContainsKey(healthRecordItemTypeIds[i]))
                {
                    permissions.Add(healthRecordItemTypeIds[i], null);
                }
            }

            request.Parameters =
                GetQueryPermissionsParametersXml(healthRecordItemTypeIds);

            request.Execute();

            XPathNavigator infoNav =
                request.Response.InfoNavigator.SelectSingleNode(
                    GetQueryPermissionsInfoXPathExpression(
                        request.Response.InfoNavigator));

            XPathNodeIterator thingTypePermissionsNodes =
                infoNav.Select("thing-type-permission");

            foreach (XPathNavigator nav in thingTypePermissionsNodes)
            {
                HealthRecordItemTypePermission thingTypePermissions =
                    HealthRecordItemTypePermission.CreateFromXml(nav);
                permissions[thingTypePermissions.TypeId] = thingTypePermissions;
            }
            return permissions;
        }
        /// <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>
        /// 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>
        /// Releases the authorization of the application on the health record.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <exception cref="HealthServiceException">
        /// Errors during the authorization release.
        /// </exception>
        /// 
        /// <remarks>
        /// Once the application releases the authorization to the health record, 
        /// calling any methods of this <see cref="HealthRecordAccessor"/> will result 
        /// in a <see cref="HealthServiceAccessDeniedException"/>."
        /// </remarks>
        public virtual void RemoveApplicationAuthorization(
            ApplicationConnection connection,
            HealthRecordAccessor accessor)
        {
            HealthServiceRequest request =
                new HealthServiceRequest(connection, "RemoveApplicationRecordAuthorization", 1, accessor);

            request.Execute();
        }
        /// <summary>
        /// Gets valid group memberships for a record.
        /// </summary>
        /// 
        /// <remarks>
        /// Group membership thing types allow an application to signify that the
        /// record belongs to an application defined group.  A record in the group may be 
        /// eligible for special programs offered by other applications, for example.  
        /// Applications then need a away to query for valid group memberships.
        /// <br/>
        /// Valid group memberships are those memberships which are not expired, and whose
        /// last updating application is authorized by the the last updating person to 
        /// read and delete the membership.
        /// </remarks>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="applicationIds">
        /// A collection of unique application identifiers for which to 
        /// search for group memberships.  For a null or empty application identifier 
        /// list, return all valid group memberships for the record.  Otherwise, 
        /// return only those group memberships last updated by one of the 
        /// supplied application identifiers.
        /// </param>
        /// 
        /// <returns>
        /// A List of HealthRecordItems representing the valid group memberships.
        /// </returns>
        /// <exception cref="HealthServiceException">
        /// If an error occurs while contacting the HealthVault service.
        /// </exception>
        public virtual Collection<HealthRecordItem> GetValidGroupMembership(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            IList<Guid> applicationIds)
        {
            StringBuilder parameters = new StringBuilder(128);
            if (applicationIds != null)
            {
                XmlWriterSettings settings = SDKHelper.XmlUnicodeWriterSettings;
                XmlWriter writer = null;
                try
                {
                    writer = XmlWriter.Create(parameters, settings);
                    for (int i = 0; i < applicationIds.Count; i++)
                    {
                        writer.WriteElementString(
                            "application-id",
                            applicationIds[i].ToString());
                    }
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Flush();
                        writer.Close();
                    }
                    writer = null;
                }
            }

            HealthServiceRequest request =
                new HealthServiceRequest(connection, "GetValidGroupMembership", 1, accessor);

            request.Parameters = parameters.ToString();
            request.Execute();

            XPathExpression infoPath =
                SDKHelper.GetInfoXPathExpressionForMethod(
                    request.Response.InfoNavigator,
                    "GetValidGroupMembership");

            XPathNavigator infoNav =
                request.Response.InfoNavigator.SelectSingleNode(infoPath);

            Collection<HealthRecordItem> memberships = new Collection<HealthRecordItem>();

            XPathNodeIterator membershipIterator = infoNav.Select("thing");
            if (membershipIterator != null)
            {
                foreach (XPathNavigator membershipNav in membershipIterator)
                {
                    memberships.Add(ItemTypeManager.DeserializeItem(membershipNav.OuterXml));
                }
            }

            return memberships;
        }
        /// <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);
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Creates a <see cref="File"/> item instance using the specified stream and content
 /// type.
 /// </summary>
 /// 
 /// <param name="record">
 /// The record to stream the data to.
 /// </param>
 /// 
 /// <param name="stream">
 /// The stream containing the data to associate with this <see cref="File"/> instance.
 /// </param>
 /// 
 /// <param name="name">
 /// The name of the file instance.
 /// </param>
 /// 
 /// <param name="contentType">
 /// The content type of the file. This is usually something like "image/jpg", "application/csv",
 /// or other mime type.
 /// </param>
 /// 
 /// <returns>
 /// A new instance of the <see cref="File"/> health record item with data populated from the
 /// specified stream.
 /// </returns>
 /// 
 /// <exception cref="ArgumentException">
 /// If <paramref name="name"/> is <b>null</b> or empty.
 /// </exception>
 /// 
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="record"/>, <paramref name="stream"/>, or 
 /// <paramref name="contentType"/> is <b>null</b>.
 /// </exception>
 /// 
 /// <exception cref="HealthServiceException">
 /// If a failure occurs streaming the data to HealthVault.
 /// </exception>
 /// 
 public static File CreateFromStream(
     HealthRecordAccessor record,
     Stream stream, 
     String name,
     CodableValue contentType)
 {
     File file = new File();
     file.SetContent(record, stream, name, contentType);
     return file;
 }
        /// <summary>
        /// Marks the specified health record item as deleted.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="itemsToRemove">
        /// The unique item identifiers of the items to remove.
        /// </param>
        /// 
        /// <remarks>
        /// This method accesses the HealthVault service across the network.
        /// <br/><br/>
        /// Health record items are never completely deleted. They are marked 
        /// as deleted and are ignored for most normal operations. Items can 
        /// be undeleted by contacting customer service.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentException">
        /// The <paramref name="itemsToRemove"/> parameter is empty.
        /// </exception>
        /// 
        /// <exception cref="HealthServiceException">
        /// Errors removed the health record items from the server.
        /// The exception's Error property will contain the index of the
        /// item on which the failure occurred in the ErrorInfo property. If any failures occur, 
        /// no items will have been removed.
        /// </exception>
        /// 
        public virtual void RemoveItems(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            IList<HealthRecordItemKey> itemsToRemove)
        {
            Validator.ThrowArgumentExceptionIf(
                itemsToRemove == null || itemsToRemove.Count == 0,
                "itemsToRemove",
                "RemoveItemsListNullOrEmpty");

            StringBuilder parameters = new StringBuilder(128 * itemsToRemove.Count);
            for (int i = 0; i < itemsToRemove.Count; ++i)
            {
                parameters.Append("<thing-id version-stamp=\"");
                parameters.Append(itemsToRemove[i].VersionStamp);
                parameters.Append("\">");
                parameters.Append(itemsToRemove[i].Id);
                parameters.Append("</thing-id>");
            }

            HealthServiceRequest request =
                new HealthServiceRequest(connection, "RemoveThings", 1, accessor);

            request.Parameters = parameters.ToString();
            request.Execute();
        }
        /// <summary>
        /// Updates the specified health record items in one batch call to 
        /// the service.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="itemsToUpdate">
        /// The health record items to be updated.
        /// </param>
        /// 
        /// <remarks>
        /// Only new items are updated with the appropriate unique identifier. 
        /// All other sections must be updated manually.
        /// <br/><br/>
        /// This method accesses the HealthVault service across the network.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="itemsToUpdate"/> parameter is <b>null</b>.
        /// </exception>
        /// 
        /// <exception cref="ArgumentException">
        /// The <paramref name="itemsToUpdate"/> contains a <b>null</b> member or
        /// a <see cref="HealthRecordItem"/> instance that does not have an ID.
        /// </exception>
        ///
        /// <exception cref="HealthServiceException">
        /// The HealthVault service returned an error.
        /// The exception's Error property will contain the index of the
        /// item on which the failure occurred in the ErrorInfo property. If any failures occur, 
        /// no items will have been updated.
        /// </exception>
        /// 
        public virtual void UpdateItems(
            ApplicationConnection connection,
            HealthRecordAccessor accessor, 
            IList<HealthRecordItem> itemsToUpdate)
        {
            Validator.ThrowIfArgumentNull(itemsToUpdate, "itemsToUpdate", "UpdateItemsArgumentNull");

            StringBuilder infoXml = new StringBuilder(128);
            XmlWriterSettings settings = SDKHelper.XmlUnicodeWriterSettings;

            bool somethingRequiresUpdate = false;

            using (XmlWriter infoXmlWriter =
                XmlWriter.Create(infoXml, settings))
            {
                foreach (HealthRecordItem item in itemsToUpdate)
                {
                    Validator.ThrowIfArgumentNull(item, "items", "UpdateItemsArgumentNull");

                    Validator.ThrowArgumentExceptionIf(
                        item.Key == null,
                        "itemsToUpdate",
                        "UpdateItemsWithNoId");

                    if (item.WriteItemXml(infoXmlWriter, false))
                    {
                        somethingRequiresUpdate = true;
                    }
                }
                infoXmlWriter.Flush();
            }

            if (somethingRequiresUpdate)
            {
                HealthServiceRequest request =
                    new HealthServiceRequest(connection, "PutThings", 2, accessor);

                // Add the XML to the request.
                request.Parameters = infoXml.ToString();

                // Call the web-service
                request.Execute();

                XPathNodeIterator thingIds =
                    request.Response.InfoNavigator.Select(
                        GetThingIdXPathExpression(request.Response.InfoNavigator));

                int index = 0;

                foreach (XPathNavigator thingIdNav in thingIds)
                {
                    HealthRecordItem thing = itemsToUpdate[index];
                    thing.Key = new HealthRecordItemKey(
                        new Guid(thingIdNav.Value),
                        new Guid(thingIdNav.GetAttribute(
                            "version-stamp", String.Empty)));
                    thing.ClearDirtyFlags();
                    ++index;
                }

            }
        }
        /// <summary>
        /// Gets the permissions which the authenticated person 
        /// has when using the calling application for the specified item types 
        /// in this health record.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="healthRecordItemTypeIds">
        /// A collection of uniqueidentifiers to identify the health record  
        /// item types, for which the permissions are being queried. 
        /// </param>
        /// 
        /// <returns>
        /// A list of <see cref="HealthRecordItemTypePermission"/> 
        /// objects which represent the permissions that the current
        /// authenticated person has for the HealthRecordItemTypes specified
        /// in the current health record when using the current application.
        /// </returns>
        /// 
        /// <remarks> 
        /// If the list of health record item types is empty, an empty list is 
        /// returned. If for a health record item type, the person has 
        /// neither online access nor offline access permissions, 
        /// HealthRecordItemTypePermission object is not returned for that
        /// health record item type. 
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="healthRecordItemTypeIds"/> is <b>null</b>.
        /// </exception>
        /// 
        /// <exception cref="HealthServiceException">
        /// If there is an exception during executing the request to HealthVault. 
        /// </exception>
        /// 
        public virtual Collection<HealthRecordItemTypePermission> QueryPermissions(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            IList<Guid> healthRecordItemTypeIds)
        {
            Validator.ThrowIfArgumentNull(healthRecordItemTypeIds, "healthRecordItemTypeIds", "CtorhealthRecordItemTypeIdsArgumentNull");

            Collection<HealthRecordItemTypePermission> permissions =
                new Collection<HealthRecordItemTypePermission>();

            HealthServiceRequest request =
                new HealthServiceRequest(connection, "QueryPermissions", 1, accessor);

            request.Parameters =
                GetQueryPermissionsParametersXml(healthRecordItemTypeIds);

            request.Execute();

            XPathNavigator infoNav =
                request.Response.InfoNavigator.SelectSingleNode(
                    GetQueryPermissionsInfoXPathExpression(
                        request.Response.InfoNavigator));

            XPathNodeIterator thingTypePermissionsNodes =
                infoNav.Select("thing-type-permission");

            foreach (XPathNavigator nav in thingTypePermissionsNodes)
            {
                HealthRecordItemTypePermission thingTypePermissions =
                    HealthRecordItemTypePermission.CreateFromXml(nav);
                permissions.Add(thingTypePermissions);
            }
            return permissions;
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Sets the content of the file instance using the specified stream.
        /// </summary>
        /// 
        /// <param name="stream">
        /// The stream containing the data to associate with this <see cref="File"/> instance.
        /// </param>
        /// 
        /// <param name="record">
        /// The record to stream the data to.
        /// </param>
        /// 
        /// <param name="name">
        /// The name of the file instance.
        /// </param>
        /// 
        /// <param name="contentType">
        /// The content type of the file.
        /// </param>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is <b>null</b> or empty.
        /// </exception>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="record"/>, <paramref name="stream"/> or <paramref name="contentType"/> is <b>null</b>.
        /// </exception>
        /// 
        /// <exception cref="HealthServiceException">
        /// If a failure occurs streaming the data to HealthVault.
        /// </exception>
        /// 
        public void SetContent(
            HealthRecordAccessor record,
            Stream stream, 
            String name,
            CodableValue contentType)
        {
            Validator.ThrowIfArgumentNull(record, "record", "FileRecordMustBeSpecified");
            Validator.ThrowIfArgumentNull(stream, "stream", "FileStreamMustBeSpecified");
            Validator.ThrowIfStringNullOrEmpty(name, "name");
            Validator.ThrowIfArgumentNull(contentType, "contentType", "FileContentTypeMustBeSpecified");

            if (stream.CanSeek)
            {
                Size = stream.Length;
            }
            Name = name;
            ContentType = contentType;

            BlobStore store = GetBlobStore(record);
            Blob blob = store.NewBlob(String.Empty, ContentType.Text);
            blob.Write(stream);
        }
        /// <summary>
        /// Disassociates an alternate ID with a record.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <param name="alternateId">
        /// The alternate ID.
        /// </param>
        /// 
        /// <remarks>
        /// This method accesses the HealthVault service across the network.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentNullException">
        /// The connection, accessor, or alternateId parameters are null.
        /// </exception>
        /// 
        /// <exception cref="ArgumentException">
        /// The alternateId parameter is empty, all whitespace, or more than 255 characters in length.
        /// </exception>
        /// 
        /// <exception cref="HealthServiceException">
        /// The HealthVault service returned an error. 
        /// If the alternate Id is not associated with a person and record id, the ErrorCode property
        /// will be set to AlternateIdNotFound.
        /// </exception>
        /// 
        public virtual void DisassociateAlternateId(
            ApplicationConnection connection,
            HealthRecordAccessor accessor,
            string alternateId)
        {
            Validator.ThrowIfArgumentNull(connection, "connection", "AlternateIdConnectionNull");
            Validator.ThrowIfArgumentNull(accessor, "accessor", "AccessorNull");
            Validator.ThrowIfArgumentNull(alternateId, "alternateId", "AlternateIdNull");

            Validator.ThrowIfStringIsEmptyOrWhitespace(alternateId, "alternateId");
            Validator.ThrowArgumentExceptionIf(alternateId.Length > 255, "alternateId", "AlternateIdTooLong");

            HealthServiceRequest request =
                new HealthServiceRequest(connection, "DisassociateAlternateId", 1, accessor);

            request.Parameters = "<alternate-id>" + alternateId + "</alternate-id>";
            request.Execute();
        }
        /// <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>
        /// Gets the list of alternate IDs that are associated with a record.
        /// </summary>
        /// 
        /// <param name="connection">
        /// The connection to use to access the data.
        /// </param>
        /// 
        /// <param name="accessor">
        /// The record to use.
        /// </param>
        /// 
        /// <remarks>
        /// This method accesses the HealthVault service across the network.
        /// </remarks>
        /// 
        /// <exception cref="HealthServiceException">
        /// The HealthVault service returned an error. 
        /// If the alternate Id is not associated with a person and record id, the ErrorCode property
        /// will be set to AlternateIdNotFound.
        /// </exception>
        /// 
        public virtual Collection<string> GetAlternateIds(
            ApplicationConnection connection,
            HealthRecordAccessor accessor)
        {
            HealthServiceRequest request =
                new HealthServiceRequest(connection, "GetAlternateIds", 1, accessor);

            request.Execute();

            Collection<string> alternateIds = new Collection<string>();

            XPathNavigator infoNav = request.Response.InfoNavigator.SelectSingleNode(
                        SDKHelper.GetInfoXPathExpressionForMethod(
                                request.Response.InfoNavigator,
                                "GetAlternateIds"));

            // Get the alternate ids that came back
            XPathNodeIterator alternateIdsNav = infoNav.Select("alternate-ids/alternate-id");

            foreach (XPathNavigator alternateIdNode in alternateIdsNav)
            {
                alternateIds.Add(alternateIdNode.Value);
            }

            return alternateIds;
        }