/// <inheritdoc />
        public void Startup(string url, string sessionId, string platformId)
        {
            ServerUrl = url;

            if (_conn == null)
            {
                if (_appState == AppState.Stopped)
                {
                    _appState = AppState.Starting;
                }

                SessionId = sessionId;

                var connection = new WebSocket();

                connection.Url = url;
                connection.Headers.Add(Constants.SessionHeader, sessionId);
                connection.Headers.Add(Constants.PlatformHeader, platformId);
                connection.Headers.Add(Constants.LegacyProtocolVersionHeader, $"{Constants.LegacyProtocolVersion}");
                connection.Headers.Add(Constants.CurrentClientVersionHeader, Constants.CurrentClientVersion);
                connection.Headers.Add(Constants.MinimumSupportedSDKVersionHeader, Constants.MinimumSupportedSDKVersion);
                connection.OnConnecting    += Conn_OnConnecting;
                connection.OnConnectFailed += Conn_OnConnectFailed;
                connection.OnConnected     += Conn_OnConnected;
                connection.OnDisconnected  += Conn_OnDisconnected;
                connection.OnError         += Connection_OnError;
                _conn = connection;
            }
            _conn.Open();
        }
        /// <inheritdoc />
        private void Disconnect()
        {
            try
            {
                if (Protocol != null)
                {
                    Protocol.Stop();
                    Protocol = new Idle(this);
                }

                if (_conn != null)
                {
                    _conn.OnConnecting    -= Conn_OnConnecting;
                    _conn.OnConnectFailed -= Conn_OnConnectFailed;
                    _conn.OnConnected     -= Conn_OnConnected;
                    _conn.OnDisconnected  -= Conn_OnDisconnected;
                    _conn.OnError         -= Connection_OnError;
                    _conn.Dispose();
                }
            }
            catch { }
            finally
            {
                _conn = null;
            }
        }
Exemplo n.º 3
0
        public void InitializeTest()
        {
            _connection      = Substitute.For <IConnectionInternal>();
            _itemTypeManager = new ThingTypeRegistrar();

            _recordId = Guid.NewGuid();
        }
        /// <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);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Gets the definition of one or more thing type definitions
 /// supported by HealthVault.
 /// </summary>
 ///
 /// <param name="typeIds">
 /// The unique identifiers for the type to get the definition of.
 /// </param>
 ///
 /// <param name="connection">
 /// A connection to the HealthVault service.
 /// </param>
 ///
 /// <returns>
 /// The type definitions for the specified types, or empty if the
 /// <paramref name="typeIds"/> parameter does not represent a known unique
 /// type identifier.
 /// </returns>
 ///
 /// <remarks>
 /// This method calls the HealthVault service if the types are not
 /// already in the client-side cache.
 /// </remarks>
 ///
 /// <exception cref="ArgumentException">
 /// If <paramref name="typeIds"/> is <b>null</b> and empty, or
 /// <paramref name="typeIds"/> is <b>null</b> and member in <paramref name="typeIds"/> is
 /// <see cref="System.Guid.Empty"/>.
 /// </exception>
 ///
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="connection"/> parameter is <b>null</b>.
 /// </exception>
 ///
 public static async Task <IDictionary <Guid, ThingTypeDefinition> > GetHealthRecordItemTypeDefinitionAsync(
     IList <Guid> typeIds,
     IConnectionInternal connection)
 {
     return(await GetHealthRecordItemTypeDefinitionAsync(
                typeIds,
                ThingTypeSections.All,
                connection).ConfigureAwait(false));
 }
Exemplo n.º 6
0
        /// <summary>
        /// Gets the definition for a thing type.
        /// </summary>
        ///
        /// <param name="typeId">
        /// The unique identifier for the type to get the definition of.
        /// </param>
        ///
        /// <param name="connection">
        /// A connection to the HealthVault service.
        /// </param>
        ///
        /// <returns>
        /// The type definition for the specified type, or <b>null</b> if the
        /// <paramref name="typeId"/> parameter does not represent a known unique
        /// type identifier.
        /// </returns>
        ///
        /// <remarks>
        /// This method calls the HealthVault service if the type is not
        /// already in the client-side cache.
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">
        /// The <paramref name="typeId"/> parameter is Guid.Empty.
        /// </exception>
        ///
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="connection"/> parameter is <b>null</b>.
        /// </exception>
        ///
        public static async Task <ThingTypeDefinition> GetHealthRecordItemTypeDefinitionAsync(
            Guid typeId,
            IConnectionInternal connection)
        {
            IDictionary <Guid, ThingTypeDefinition> typeDefs =
                await GetHealthRecordItemTypeDefinitionAsync(new[] { typeId }, connection).ConfigureAwait(false);

            return(typeDefs[typeId]);
        }
        public RequestMessageCreator(
            IConnectionInternal connectionInternal,
            IServiceLocator serviceLocator)
        {
            _connectionInternal = connectionInternal;

            _healthVaultConfiguration = serviceLocator.GetInstance <HealthVaultConfiguration>();
            _telemetryInformation     = serviceLocator.GetInstance <SdkTelemetryInformation>();
            _cryptographer            = serviceLocator.GetInstance <ICryptographer>();
        }
        public WebSessionCredentialClient(
            IServiceLocator serviceLocator,
            IConnectionInternal connection,
            ICertificateInfoProvider certificateInfoProvider)
        {
            _serviceLocator         = serviceLocator;
            Connection              = connection;
            CertificateInfoProvider = certificateInfoProvider;

            _webHealthVaultConfiguration = serviceLocator.GetInstance <WebHealthVaultConfiguration>();
        }
Exemplo n.º 9
0
 /// <summary>
 /// Gets the requested thing type definitions supported by HealthVault
 /// only if they have been updated since the specified last client refresh date.
 /// </summary>
 ///
 /// <param name="typeIds">
 /// A collection of health item type IDs whose details are being requested. Null
 /// indicates that all health item types should be returned.
 /// </param>
 ///
 /// <param name="sections">
 /// A collection of ThingTypeSections enumeration values that indicate the type of
 /// details to be returned for the specified health item record(s).
 /// </param>
 ///
 /// <param name="lastClientRefreshDate">
 /// An <see cref="Instant"/> that specifies the time of the last refresh
 /// made by the client.
 /// </param>
 ///
 /// <param name="connection">
 /// A connection to the HealthVault service.
 /// </param>
 ///
 /// <returns>
 /// The type definitions for the specified types, or empty if the
 /// <paramref name="typeIds"/> parameter does not represent a known unique
 /// type identifier.
 /// </returns>
 ///
 /// <remarks>
 /// This method calls the HealthVault service if the types are not
 /// already in the client-side cache.
 /// </remarks>
 ///
 /// <exception cref="ArgumentException">
 /// If <paramref name="typeIds"/> is <b>null</b> and empty, or
 /// <paramref name="typeIds"/> is <b>null</b> and member in <paramref name="typeIds"/> is
 /// <see cref="System.Guid.Empty"/>.
 /// </exception>
 ///
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="connection"/> parameter is <b>null</b>.
 /// </exception>
 ///
 public static async Task <IDictionary <Guid, ThingTypeDefinition> > GetHealthRecordItemTypeDefinitionAsync(
     IList <Guid> typeIds,
     ThingTypeSections sections,
     Instant?lastClientRefreshDate,
     IConnectionInternal connection)
 {
     return(await GetHealthRecordItemTypeDefinitionAsync(
                typeIds,
                sections,
                null,
                lastClientRefreshDate,
                connection).ConfigureAwait(false));
 }
        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>());
        }
        public void InitializeTest()
        {
            _connection = Substitute.For <IConnectionInternal>();
            _client     = new VocabularyClient(_connection);

            var response = new HealthServiceResponseData
            {
                InfoNavigator = new XPathDocument(new StringReader(SampleUtils.GetSampleContent("VocabularySample.xml"))).CreateNavigator(),
            };

            _connection.ExecuteAsync(Arg.Any <HealthVaultMethods>(), Arg.Any <int>(), Arg.Any <string>())
            .Returns(response);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates an instance of a HealthRecordAccessor object using
        /// the specified XML.
        /// </summary>
        ///
        /// <param name="connection">
        /// A connection for the current user.
        /// </param>
        ///
        /// <param name="navigator">
        /// The XML containing the record information.
        /// </param>
        ///
        /// <returns>
        /// A new instance of a HealthRecordAccessor object containing the
        /// record information.
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="connection"/> or <paramref name="navigator"/>
        /// parameter is <b>null</b>.
        /// </exception>
        ///
        public static HealthRecordAccessor CreateFromXml(
            IConnectionInternal connection,
            XPathNavigator navigator)
        {
            Validator.ThrowIfArgumentNull(connection, nameof(connection), Resources.PersonInfoConnectionNull);
            Validator.ThrowIfArgumentNull(navigator, nameof(navigator), Resources.ParseXmlNavNull);

            HealthRecordAccessor recordInfo =
                new HealthRecordAccessor(connection);

            recordInfo.ParseXml(navigator);
            return(recordInfo);
        }
        public void InitializeTest()
        {
            _connection     = Substitute.For <IConnectionInternal>();
            _serviceLocator = Substitute.For <IServiceLocator>();

            _serviceLocator.GetInstance <HealthVaultConfiguration>()
            .Returns(new HealthVaultConfiguration
            {
                MasterApplicationId       = Guid.NewGuid(),
                RequestTimeToLiveDuration = new TimeSpan(hours: 0, minutes: 1, seconds: 5)
            });

            _serviceLocator.GetInstance <SdkTelemetryInformation>()
            .Returns(
                new SdkTelemetryInformation()
            {
                Category = "test", FileVersion = "test", OsInformation = "test"
            });

            ICryptographer mockCryptographer = Substitute.For <ICryptographer>();
            CryptoData     mockCryptoData    = new CryptoData()
            {
                Algorithm = "some", Value = "some"
            };

            mockCryptographer.Hmac(Arg.Any <string>(), Arg.Any <byte[]>())
            .Returns(mockCryptoData);

            mockCryptographer.Hash(Arg.Any <byte[]>())
            .Returns(mockCryptoData);

            _serviceLocator.GetInstance <ICryptographer>().Returns(mockCryptographer);

            _connection.SessionCredential.Returns(
                new SessionCredential()
            {
                SharedSecret = "someSharedSecret", Token = "someToken"
            });
        }
Exemplo n.º 14
0
        /// <inheritdoc />
        public void Startup(string url, string sessionId, string platformId)
        {
            ServerUri      = new Uri(url, UriKind.Absolute);
            ServerAssetUri = new Uri(Regex.Replace(ServerUri.AbsoluteUri, "^ws(s?):", "http$1:"));

            if (UsePhysicsBridge)
            {
                _actorManager.RigidBodyAdded             += OnRigidBodyAdded;
                _actorManager.RigidBodyRemoved           += OnRigidBodyRemoved;
                _actorManager.RigidBodyKinematicsChanged += OnRigidBodyKinematicsChanged;
                _actorManager.RigidBodyOwnerChanged      += OnRigidBodyOwnerChanged;
            }

            if (_conn == null)
            {
                if (_appState == AppState.Stopped)
                {
                    _appState = AppState.Starting;
                }

                SessionId = sessionId;

                var connection = new WebSocket();

                connection.Url = url;
                connection.Headers.Add(Constants.SessionHeader, sessionId);
                connection.Headers.Add(Constants.PlatformHeader, platformId);
                connection.Headers.Add(Constants.LegacyProtocolVersionHeader, $"{Constants.LegacyProtocolVersion}");
                connection.Headers.Add(Constants.CurrentClientVersionHeader, Constants.CurrentClientVersion);
                connection.Headers.Add(Constants.MinimumSupportedSDKVersionHeader, Constants.MinimumSupportedSDKVersion);
                connection.OnConnecting    += Conn_OnConnecting;
                connection.OnConnectFailed += Conn_OnConnectFailed;
                connection.OnConnected     += Conn_OnConnected;
                connection.OnDisconnected  += Conn_OnDisconnected;
                connection.OnError         += Connection_OnError;
                _conn = connection;
            }
            _conn.Open();
        }
 public void InitializeTest()
 {
     _connection   = Substitute.For <IConnectionInternal>();
     _personClient = new PersonClient(_connection);
 }
Exemplo n.º 16
0
        /// <inheritdoc />
        public async void Startup(string url, string sessionId)
        {
            if (_appState != AppState.Stopped)
            {
                Shutdown();
            }

            ServerUri      = new Uri(url, UriKind.Absolute);
            ServerAssetUri = new Uri(Regex.Replace(ServerUri.AbsoluteUri, "^ws(s?):", "http$1:"));
            SessionId      = sessionId;

            _appState = AppState.WaitingForPermission;

            // download manifest
            var         manifestUri = new Uri(ServerAssetUri, "./manifest.json");
            AppManifest manifest;

            try
            {
                manifest = await AppManifest.DownloadManifest(manifestUri);
            }
            catch (Exception e)
            {
                Debug.LogErrorFormat("Error downloading MRE manifest \"{0}\":\n{1}", manifestUri, e.ToString());
                manifest = new AppManifest()
                {
                    OptionalPermissions = new Permissions[] { Permissions.UserTracking, Permissions.UserInteraction }
                };
            }

            var neededFlags = Permissions.Execution | (manifest.Permissions?.ToFlags() ?? Permissions.None);
            var wantedFlags = manifest.OptionalPermissions?.ToFlags() ?? Permissions.None;

            // get permission to run from host app
            var grantedPerms = await MREAPI.AppsAPI.PermissionManager.PromptForPermissions(
                appLocation : ServerUri,
                permissionsNeeded : new HashSet <Permissions>(manifest.Permissions ?? new Permissions[0])
            {
                Permissions.Execution
            },
                permissionsWanted : manifest.OptionalPermissions,
                permissionFlagsNeeded : neededFlags,
                permissionFlagsWanted : wantedFlags,
                appManifest : manifest);

            // only use permissions that are requested, even if the user offers more
            GrantedPermissions = grantedPerms & (neededFlags | wantedFlags);

            MREAPI.AppsAPI.PermissionManager.OnPermissionDecisionsChanged += OnPermissionsUpdated;

            if (!grantedPerms.HasFlag(Permissions.Execution))
            {
                Debug.LogError($"User has denied permission for the MRE '{ServerUri}' to run");
                return;
            }

            _appState = AppState.Starting;

            var connection = new WebSocket();

            connection.Url = url;
            connection.Headers.Add(Constants.SessionHeader, SessionId);
            connection.Headers.Add(Constants.LegacyProtocolVersionHeader, $"{Constants.LegacyProtocolVersion}");
            connection.Headers.Add(Constants.CurrentClientVersionHeader, Constants.CurrentClientVersion);
            connection.Headers.Add(Constants.MinimumSupportedSDKVersionHeader, Constants.MinimumSupportedSDKVersion);
            connection.OnConnecting    += Conn_OnConnecting;
            connection.OnConnectFailed += Conn_OnConnectFailed;
            connection.OnConnected     += Conn_OnConnected;
            connection.OnDisconnected  += Conn_OnDisconnected;
            connection.OnError         += Connection_OnError;
            _conn = connection;
            _conn.Open();
        }
Exemplo n.º 17
0
 /// <summary>
 /// Gets the thing type definition for the base item type.
 /// </summary>
 ///
 /// <param name="connection">
 /// A connection to the HealthVault service.
 /// </param>
 ///
 /// <remarks>
 /// The base item type is a constructed item type that contains
 /// definitions of the standard item transforms that will work
 /// for any item type. If a specific item type does not define a
 /// standard transformation, the base item type transformation can
 /// be used instead.
 /// <br/><br/>
 /// This method calls the HealthVault service if the type is not
 /// already in the client-side cache.
 /// </remarks>
 ///
 /// <exception cref="ArgumentNullException">
 /// The <paramref name="connection"/> parameter is <b>null</b>.
 /// </exception>
 ///
 public static async Task <ThingTypeDefinition> GetBaseHealthRecordItemTypeDefinitionAsync(
     IConnectionInternal connection)
 {
     return(await GetHealthRecordItemTypeDefinitionAsync(s_baseTypeId, connection).ConfigureAwait(false));
 }
        /// <inheritdoc />
        public async void Startup(string url, string sessionId)
        {
            if (_appState != AppState.Stopped)
            {
                Shutdown();
            }

            ServerUri      = new Uri(url, UriKind.Absolute);
            ServerAssetUri = new Uri(Regex.Replace(ServerUri.AbsoluteUri, "^ws(s?):", "http$1:"));
            SessionId      = sessionId;

            _appState = AppState.WaitingForPermission;
            OnWaitingForPermission?.Invoke();

            // download manifest
            var         manifestUri = new Uri(ServerAssetUri, "./manifest.json");
            AppManifest manifest;

            try
            {
                manifest = await AppManifest.DownloadManifest(manifestUri);
            }
            catch (Exception e)
            {
                var errMessage = String.Format("Error downloading MRE manifest \"{0}\":\n{1}", manifestUri, e.ToString());
                GD.PushError(errMessage);
                manifest = new AppManifest()
                {
                    Permissions = new Permissions[] { Permissions.UserTracking, Permissions.UserInteraction }
                };
            }

            var neededFlags = Permissions.Execution | (manifest.Permissions?.ToFlags() ?? Permissions.None);
            var wantedFlags = manifest.OptionalPermissions?.ToFlags() ?? Permissions.None;

            // set up cancel source
            if (permissionRequestCancelSource != null)
            {
                permissionRequestCancelSource.Cancel();
            }
            permissionRequestCancelSource = new CancellationTokenSource();

            // get permission to run from host app
            var grantedPerms = await MREAPI.AppsAPI.PermissionManager.PromptForPermissions(
                appLocation : ServerUri,
                permissionsNeeded : new HashSet <Permissions>(manifest.Permissions ?? new Permissions[0])
            {
                Permissions.Execution
            },
                permissionsWanted : manifest.OptionalPermissions,
                permissionFlagsNeeded : neededFlags,
                permissionFlagsWanted : wantedFlags,
                appManifest : manifest,
                cancellationToken : permissionRequestCancelSource.Token);

            // clear cancel source once we don't need it anymore
            permissionRequestCancelSource = null;

            // only use permissions that are requested, even if the user offers more
            GrantedPermissions = grantedPerms & (neededFlags | wantedFlags);

            MREAPI.AppsAPI.PermissionManager.OnPermissionDecisionsChanged += OnPermissionsUpdated;

            // make sure all needed perms are granted
            if (!GrantedPermissions.HasFlag(neededFlags))
            {
                OnPermissionDenied?.Invoke();
                Shutdown(reactivateOnPermissions: true);
                return;
            }

            _appState = AppState.Starting;

            var connection = new WebSocket();

            connection.Url = url;
            connection.Headers.Add(Constants.SessionHeader, SessionId);
            connection.Headers.Add(Constants.LegacyProtocolVersionHeader, $"{Constants.LegacyProtocolVersion}");
            connection.Headers.Add(Constants.CurrentClientVersionHeader, Constants.CurrentClientVersion);
            connection.Headers.Add(Constants.MinimumSupportedSDKVersionHeader, Constants.MinimumSupportedSDKVersion);
            connection.OnConnecting    += Conn_OnConnecting;
            connection.OnConnectFailed += Conn_OnConnectFailed;
            connection.OnConnected     += Conn_OnConnected;
            connection.OnDisconnected  += Conn_OnDisconnected;
            connection.OnError         += Connection_OnError;
            _conn = connection;
            _conn.Open();
        }
        private async Task <ThingDataTableView> ApplyEffectiveViewAsync(
            IConnectionInternal connection)
        {
            ThingDataTableView effectiveView =
                ThingDataTableView.MultipleTypeTable;

            ThingTypeDefinition typeDefinition = null;

            if (Query.TypeIds.Count == 1 &&
                View != ThingDataTableView.MultipleTypeTable)
            {
                typeDefinition =
                    await ItemTypeManager.GetHealthRecordItemTypeDefinitionAsync(
                        this.Query.TypeIds[0],
                        connection).ConfigureAwait(false);

                ThingTypeDefinitionHelper thingTypeDefinitionHelper = null;

                if (typeDefinition != null)
                {
                    thingTypeDefinitionHelper = ThingTypeDefinitionHelper.Create(typeDefinition);
                }

                if (thingTypeDefinitionHelper != null &&
                    thingTypeDefinitionHelper.ColumnDefinitions.Count > 0)
                {
                    effectiveView
                        = ThingDataTableView.SingleTypeTable;
                    _singleTypeDefinition = typeDefinition;

                    foreach (
                        ItemTypeDataColumn column in
                        thingTypeDefinitionHelper.ColumnDefinitions)
                    {
                        _displayColumns.Add(
                            column.ColumnName, column.Clone());
                    }

                    this.Query.View.TransformsToApply.Clear();
                    this.Query.View.TransformsToApply.Add("stt");
                }
            }

            if (_singleTypeDefinition == null)
            {
                typeDefinition =
                    await ItemTypeManager.GetBaseHealthRecordItemTypeDefinitionAsync(
                        connection).ConfigureAwait(false);

                effectiveView
                    = ThingDataTableView.MultipleTypeTable;

                if (typeDefinition != null)
                {
                    var healthRecordItemTypeDefinitionHelper = ThingTypeDefinitionHelper.Create(typeDefinition);

                    foreach (
                        ItemTypeDataColumn column in
                        healthRecordItemTypeDefinitionHelper.ColumnDefinitions)
                    {
                        _displayColumns.Add(column.ColumnName, column.Clone());
                    }

                    this.Query.View.TransformsToApply.Clear();
                    this.Query.View.TransformsToApply.Add("mtt");
                }
            }

            return(effectiveView);
        }
Exemplo n.º 20
0
 /// <summary>
 /// Gets the definitions for all thing type definitions
 /// supported by HealthVault.
 /// </summary>
 ///
 /// <param name="sections">
 /// A collection of ThingTypeSections enumeration values that indicate the type of
 /// details to be returned for the specified health item record(s).
 /// </param>
 ///
 /// <param name="connection">
 /// A connection to the HealthVault service.
 /// </param>
 ///
 /// <returns>
 /// The type definitions for all the thing type definitions
 /// supported by HealthVault.
 /// </returns>
 ///
 /// <remarks>
 /// This method calls the HealthVault service if the types are not
 /// already in the client-side cache.
 /// </remarks>
 ///
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="connection"/> parameter is <b>null</b>.
 /// </exception>
 ///
 public static async Task <IDictionary <Guid, ThingTypeDefinition> > GetHealthRecordItemTypeDefinitionAsync(
     ThingTypeSections sections,
     IConnectionInternal connection)
 {
     return(await GetHealthRecordItemTypeDefinitionAsync(null, sections, null, null, connection).ConfigureAwait(false));
 }