Example #1
0
        public override void SampleCall(string[] args)
        {
            #region Parse Arguments
            ArgParser cmdLineParser = new ArgParser();
            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            #endregion

            #region Initialize Properties
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            InitContext(cmdLineParser.LogLevel);

            using (Requestor requestor = new Requestor(contextProps, sessionProps))
                using (Responder responder = new Responder(contextProps, sessionProps))
                {
                    requestor.SendTo(responder.ReceivingOn);
                    requestor.Commit();

                    Log.Start("Waiting for message");
                    Log.AssertTrue(requestor.WaitForMessage(15000),
                                   "Timeout while waiting for message");
                }
        }
Example #2
0
        public override IEnumerable <string> Process(string rootDirectory)
        {
            var subdirs = SampleUtils.GetDatasets(rootDirectory);

            var format = new BreastCancerSampleItemFormat();

            List <BreastCancerSampleItem> total = new List <BreastCancerSampleItem>();

            foreach (var subdir in subdirs)
            {
                var parser = ParserFactory.GetParserInDirectory(subdir);

                var dirname = Path.GetFileName(subdir);
                Console.WriteLine(dirname);

                Dictionary <string, BreastCancerSampleItem> flist = new Dictionary <string, BreastCancerSampleItem>();
                parser.ParseDataset(subdir, flist);

                total.AddRange(flist.Values);

                var sampleFile = subdir + @"\" + dirname + ".sample";
                format.WriteToFile(sampleFile, flist.Values.ToList());
            }

            var htmlFile = rootDirectory + "\\" + Path.GetFileNameWithoutExtension(rootDirectory) + "_SampleInformation.html";

            new BreastCancerSampleItemHtmlWriter().WriteToFile(htmlFile, total);

            var excelFile = Path.ChangeExtension(htmlFile, ".xls");

            new BreastCancerSampleItemExcelWriter().WriteToFile(excelFile, total);

            return(new string[] { htmlFile, excelFile });
        }
        public static void CanScanSingleFiles()
        {
            // Arrange
            string path, name;

            do
            {
                name = Path.GetRandomFileName();
                path = Path.Combine(Path.GetTempPath(), name + ".xml");
            } while (Directory.Exists(path));

            File.WriteAllText(path, null);

            // Act
            var result = SampleUtils.LoadXmlSamples(new[] { path }, false);

            // Assert
            try
            {
                Assert.AreEqual(1, result.Items.Count);
                Assert.AreEqual(name, result.Items[0].Name);
            }
            finally
            {
                File.Delete(path);
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Invalid parameters.  Usage is split.exe <filename>");
                Console.WriteLine("You can only split STEREO files.");
                return;
            }

            using (var streamIn = new FileStream(args[0], FileMode.Open))
            {
                var info = FileHeaderUtil.GetHeaderInfo(streamIn);

                if (info.Channels != Channel.Mono)
                {
                    throw new InvalidDataException();
                }

                info.SampleCount *= 2;
                info.Channels     = Channel.Stereo;

                var outputStream = Console.OpenStandardOutput();
                FileHeaderUtil.WriteHeaderInfo(outputStream, info);

                while (streamIn.Length != streamIn.Position)
                {
                    var sample = SampleUtils.ReadSample(streamIn, info);
                    SampleUtils.WriteSample(sample, outputStream, info);
                    SampleUtils.WriteSample(sample, outputStream, info);
                }
            }
        }
        public static void CanScanFolder(int numFiles, int numFolders, int nestedLevels)
        {
            // Arrange: create a random folder / xml file structure
            string root;

            do
            {
                root = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            } while (Directory.Exists(root));

            Directory.CreateDirectory(root);
            var expected = PopulateRandomly(root, numFiles, numFolders, nestedLevels);

            // Act
            var result = SampleUtils.LoadXmlSamples(new[] { root }, false);

            // Assert
            try
            {
                AssertConsistency(expected, (SampleFolderViewModel)result.Items[0]);
            }
            finally
            {
                Directory.Delete(root, true);
            }
        }
Example #6
0
        public void CreateClient()
        {
            InitializeResponse(SampleUtils.GetSampleContent("ThingsSampleBloodPressure.xml"));
            var guid = Guid.NewGuid();

            _client.CorrelationId = guid;
            Assert.IsTrue(_client.CorrelationId == guid);
        }
Example #7
0
        private BloodGlucose CreateSampleBloodGlucose()
        {
            BloodGlucose thing    = new BloodGlucose();
            var          document =
                new XPathDocument(new StringReader(SampleUtils.GetSampleContent("ThingSample.xml")));

            thing.ParseXml(document.CreateNavigator().SelectSingleNode("thing"), SampleUtils.GetSampleContent("ThingSample.xml"));
            return(thing);
        }
        public static void CanScanAssemblySamples()
        {
            // Act
            var result = SampleUtils.LoadXmlSamples(Enumerable.Empty <string>(), true);

            // Assert
            ScanResult(result, x => Assert.False(x is FileSampleViewModel));
            Assert.IsNotEmpty(result.Items);
        }
 private static bool IsDeviceEnabled(TelemetryAudienceType audienceType, string dpti)
 {
     if (audienceType == TelemetryAudienceType.PreProduction)
     {
         // Pre-production should never be sampled
         return(true);
     }
     return(SampleUtils.ShouldEnableDevice(dpti));
 }
Example #10
0
        static void Main(string[] args)
        {
            if (args.Length != 6)
            {
                Console.WriteLine("Invalid number of parameters.");
                Console.WriteLine("Usage is gensine.exe <channels> <frequency> <sample size> <sample rate> <amplitude> <duration>");
                Console.WriteLine("<channels> := Mono, Stereo");
                Console.WriteLine("<frequency> := int (Hz)");
                Console.WriteLine("<sample size> := 8, 16, 24, or 32");
                Console.WriteLine("<sample rate> := int (samples/sec)");
                Console.WriteLine("<amplitude> := int");
                Console.WriteLine("<duration> := double (seconds)");
                return;
            }

            Channel channels   = (Channel)Enum.Parse(typeof(Channel), args[0], true);
            int     frequency  = int.Parse(args[1]);
            int     sampleSize = int.Parse(args[2]);
            int     sampleRate = int.Parse(args[3]);
            int     amplitude  = int.Parse(args[4]);
            double  duration   = double.Parse(args[5]);

            var info = new FileInfo
            {
                Channels    = channels,
                Frequency   = sampleRate,
                SampleBits  = sampleSize,
                SampleCount = (int)(sampleRate * duration)
            };

            double samplesPerCycle = sampleRate / (double)frequency;
            double interval        = 2 * Math.PI / samplesPerCycle;
            double offset          = 0;

            var outputStream = Console.OpenStandardOutput();

            FileHeaderUtil.WriteHeaderInfo(outputStream, info);

            for (int i = 0; i < info.SampleCount; i++)
            {
                if (offset > 2 * Math.PI)
                {
                    offset -= 2 * Math.PI;
                }

                uint sample = (uint)(((Math.Sin(offset) + 1) * amplitude / 2.0) + (amplitude / 2.0));

                SampleUtils.WriteSample(sample, outputStream, info);
                if (info.Channels == Channel.Stereo)
                {
                    SampleUtils.WriteSample(sample, outputStream, info);
                }

                offset += interval;
            }
        }
Example #11
0
        public async Task CreateNewThings()
        {
            InitializeResponse(SampleUtils.GetSampleContent("ThingsSampleBloodPressure.xml"));
            ICollection <IThing> things = new Collection <IThing> {
                CreateSampleBloodGlucose()
            };
            await _client.CreateNewThingsAsync(_recordId, things);

            await _connection.Received().ExecuteAsync(HealthVaultMethods.PutThings, Arg.Any <int>(), Arg.Is <string>(x => x.Contains("blood-glucose")), Arg.Is <Guid>((x) => x == _recordId));
        }
Example #12
0
        public void EightBitSample_ReadOneSample_ReturnsSample()
        {
            var stream = new MemoryStream(new byte[] { 0x1 });
            var info   = new FileInfo {
                Channels = Channel.Mono, Frequency = 1, SampleBits = 8, SampleCount = 1
            };

            var actual = SampleUtils.ReadSample(stream, info);

            Assert.AreEqual(0x1, actual);
        }
Example #13
0
        public async Task GetTypedThings()
        {
            InitializeResponse(SampleUtils.GetSampleContent("ThingsSampleBloodPressure.xml"));
            var query  = this.GetBloodPressureThingQuery();
            var result = await _client.GetThingsAsync <BloodPressure>(_recordId, query);

            await _connection.Received().ExecuteAsync(HealthVaultMethods.GetThings, Arg.Any <int>(), Arg.Is <string>(x => x.Contains(BloodPressure.TypeId.ToString())), Arg.Is <Guid>((x) => x == _recordId));

            // Assert that non-Blood Pressure results were filtered
            Assert.AreEqual(30, result.Count);
        }
Example #14
0
        public async Task RemoveThings()
        {
            InitializeResponse(SampleUtils.GetSampleContent("ThingsSampleBloodPressure.xml"));
            var thing = CreateSampleBloodGlucose();
            ICollection <IThing> things = new Collection <IThing> {
                thing
            };
            await _client.RemoveThingsAsync(_recordId, things);

            await _connection.Received().ExecuteAsync(HealthVaultMethods.RemoveThings, Arg.Any <int>(), Arg.Is <string>(x => x.Contains(thing.Key.Id.ToString())), Arg.Is <Guid>((x) => x == _recordId));
        }
        public async Task SetApplicationSettingsWitXPathNavTest()
        {
            var response = SampleUtils.GetResponseData("AppSettingsSample.xml");

            var nav = response.InfoNavigator;

            await _personClient.SetApplicationSettingsAsync(nav).ConfigureAwait(false);

            await _connection.Received()
            .ExecuteAsync(HealthVaultMethods.SetApplicationSettings, Arg.Any <int>(), Arg.Is <string>(x => x.Contains("7a231675-4e78-451f-b94d-1e05b2a24586")));
        }
        public async Task GetApplicationSettingsTest()
        {
            var response = SampleUtils.GetResponseData("AppSettingsSample.xml");

            _connection.ExecuteAsync(HealthVaultMethods.GetApplicationSettings, Arg.Any <int>()).Returns(response);

            var result = await _personClient.GetApplicationSettingsAsync();

            await _connection.Received().ExecuteAsync(HealthVaultMethods.GetApplicationSettings, Arg.Any <int>(), null);

            Assert.IsNotNull(result.SelectedRecordId);
        }
Example #17
0
        public async Task GetServiceDefinitionWithSectionsTest()
        {
            var response = SampleUtils.GetResponseData("ServiceDefinitionSample.xml");

            _connection.ExecuteAsync(HealthVaultMethods.GetServiceDefinition, Arg.Any <int>(), Arg.Any <string>())
            .Returns(response);
            var result = await _platformClient.GetServiceDefinitionAsync(ServiceInfoSections.All).ConfigureAwait(false);

            await _connection.Received()
            .ExecuteAsync(HealthVaultMethods.GetServiceDefinition, Arg.Any <int>(), Arg.Any <string>());

            Assert.AreEqual("2017-03-17T03:24:19Z", result.LastUpdated.ToString());
        }
Example #18
0
        public async Task NormalRead()
        {
            _subSecretStore.ReadAsync(ServiceInstanceKey).Returns(SampleUtils.GetSampleContent(ServiceInstanceSampleFile));

            LocalObjectStore      localObjectStore = CreateLocalObjectStore();
            HealthServiceInstance serviceInstance  = await localObjectStore.ReadAsync <HealthServiceInstance>(ServiceInstanceKey);

            Assert.AreEqual("test", serviceInstance.Id);
            Assert.AreEqual("Test", serviceInstance.Name);
            Assert.AreEqual("description", serviceInstance.Description);
            Assert.AreEqual(new Uri("http://contoso.com"), serviceInstance.HealthServiceUrl);
            Assert.AreEqual(new Uri("http://contoso.com/shell"), serviceInstance.ShellUrl);
        }
        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);
        }
Example #20
0
        public void ThirtyTwoBitSample_ReadOneSample_ReturnsSample()
        {
            var stream = new MemoryStream(new byte[] { 0x1, 0x2, 0x3, 0x4 });
            var info   = new FileInfo {
                Channels = Channel.Mono, Frequency = 1, SampleBits = 32, SampleCount = 1
            };

            var actual = SampleUtils.ReadSample(stream, info);

            const int expected = 0x1 | (0x2 << 8) | (0x3 << 16) | (0x4 << 24);

            Assert.AreEqual(expected, actual);
        }
        /// <summary>
        /// Demonstrates message acknoweldgment of received messages over the Flow.
        /// ClientAck on the Flow is enabled by setting flowProps.AckMode to MessageAckMode.ClientAck.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        internal void HandleMessageAndAck(Object source, MessageEventArgs args)
        {
            // Print the message.
            SampleUtils.PrintMessageEvent(source, args);

            // Acknowledge incoming message after it has been processed.
            if (flow != null)
            {
                flow.Ack(args.Message.ADMessageId);
            }

            // It is recommended to dispose the message after processing it.
            args.Message.Dispose();
        }
        public async Task SearchVocabulariesTest()
        {
            var response = new HealthServiceResponseData
            {
                InfoNavigator = new XPathDocument(new StringReader(SampleUtils.GetSampleContent("VocabularySearchSample.xml"))).CreateNavigator()
            };

            _connection.ExecuteAsync(Arg.Any <HealthVaultMethods>(), Arg.Any <int>(), Arg.Any <string>())
            .Returns(response);
            var searchTerm = "hypertension";
            await _client.SearchVocabularyAsync(searchTerm, VocabularySearchType.Contains, null);

            await _connection.Received().ExecuteAsync(HealthVaultMethods.SearchVocabulary, Arg.Any <int>(), Arg.Is <string>(x => x.Contains(searchTerm)));
        }
        public async Task GetAuthorizedPeopleTest()
        {
            string requestParameters = "<parameters />";
            var    personId          = new Guid("2d44d876-3bde-482b-a2af-ba133bc41fa9");

            var response = SampleUtils.GetResponseData("AuthorizedPeopleSample.xml");

            _connection.ExecuteAsync(HealthVaultMethods.GetAuthorizedPeople, Arg.Any <int>(), Arg.Any <string>()).Returns(response);
            var result = (await _personClient.GetAuthorizedPeopleAsync()).FirstOrDefault();

            await _connection.Received().ExecuteAsync(HealthVaultMethods.GetAuthorizedPeople, Arg.Any <int>(), Arg.Is <string>(x => x.Contains(requestParameters)));

            Assert.IsNotNull(result);
            Assert.AreEqual(result.PersonId, personId);
        }
Example #24
0
        public async Task GetServiceDefinitionWithDateTimeTest()
        {
            Instant lastUpdatedTime = Instant.FromDateTimeOffset(new DateTimeOffset(2017, 03, 17, 03, 24, 19, TimeSpan.Zero));
            var     response        = SampleUtils.GetResponseData("ServiceDefinitionSample.xml");

            _connection.ExecuteAsync(HealthVaultMethods.GetServiceDefinition, Arg.Any <int>(), Arg.Any <string>())
            .Returns(response);

            var result = await _platformClient.GetServiceDefinitionAsync(lastUpdatedTime).ConfigureAwait(false);

            await _connection.Received()
            .ExecuteAsync(HealthVaultMethods.GetServiceDefinition, Arg.Any <int>(), Arg.Any <string>());

            Assert.AreEqual(lastUpdatedTime, result.LastUpdated);
        }
        public void WhenDeserializesXml_ThenCorrectSerializationReturned()
        {
            // Note: This test assumes we don't need a Connection while deserializing this xml.
            var deserializer = new ThingDeserializer(null, new ThingTypeRegistrar());
            var xml          = SampleUtils.GetSampleContent("ThingSampleWeight.xml");
            var weight       = deserializer.Deserialize(xml) as Weight;

            Assert.IsNotNull(weight);
            Assert.AreEqual(new Guid("31501360-362b-4791-ae12-141386ac5da6"), weight.Key.Id);
            Assert.AreEqual(new Guid("672b1c15-4704-4bcd-97d6-3e183309af0a"), weight.Key.VersionStamp);
            Assert.AreEqual(new NodaTime.LocalDateTime(2017, 6, 2, 0, 0, 0), weight.EffectiveDate);
            Assert.AreEqual(new HealthServiceDateTime(new HealthServiceDate(2017, 6, 2)), weight.When);
            Assert.AreEqual(76, weight.Value.Kilograms);
            Assert.AreEqual("kg", weight.Value.DisplayValue.Units);
            Assert.AreEqual("kg", weight.Value.DisplayValue.UnitsCode);
        }
Example #26
0
        public async Task SelectInstanceTest()
        {
            var location = new Location("US", "WA");

            var response = SampleUtils.GetResponseData("InstanceSample.xml");

            _connection.ExecuteAsync(HealthVaultMethods.SelectInstance, Arg.Any <int>(), Arg.Any <string>())
            .Returns(response);

            var result = await _platformClient.SelectInstanceAsync(location).ConfigureAwait(false);

            await _connection.Received()
            .ExecuteAsync(HealthVaultMethods.SelectInstance, Arg.Any <int>(), Arg.Any <string>());

            Assert.AreEqual("US instance", result.Description);
        }
Example #27
0
        public async Task NormalWrite()
        {
            var serviceInstance = new HealthServiceInstance
            {
                Id               = "test",
                Name             = "Test",
                Description      = "description",
                HealthServiceUrl = new Uri("http://contoso.com"),
                ShellUrl         = new Uri("http://contoso.com/shell"),
            };

            LocalObjectStore localObjectStore = CreateLocalObjectStore();
            await localObjectStore.WriteAsync(ServiceInstanceKey, serviceInstance);

            await _subSecretStore.Received().WriteAsync(ServiceInstanceKey, SampleUtils.GetSampleContent(ServiceInstanceSampleFile));
        }
Example #28
0
        public async Task GetThings()
        {
            InitializeResponse(SampleUtils.GetSampleContent("ThingsSampleBloodPressure.xml"));
            ThingQuery query  = this.GetBloodPressureThingQuery();
            var        result = await _client.GetThingsAsync(_recordId, query);

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

            // Assert that all results are parsed, grouped, and returned correctly.
            // Note that the sample data was not from this exact call, so it includes some other types of things in the results
            Assert.AreEqual(33, result.Count);
        }
Example #29
0
        public static uint[] ReadSamples(Stream readFrom, int startAt, int windowSize, FileInfo info)
        {
            readFrom.Seek(-((info.SampleBits / 8) * (info.SampleCount - startAt)), SeekOrigin.End);
            uint[] samples = new uint[windowSize];

            int i = 0;

            for (; i < windowSize; i++)
            {
                samples[i] = SampleUtils.ReadSample(readFrom, info);
                if (info.Channels == Channel.Stereo)
                {
                    SampleUtils.ReadSample(readFrom, info);
                }
            }

            return(samples);
        }
Example #30
0
        public async Task GetThing()
        {
            InitializeResponse(SampleUtils.GetSampleContent("ThingSampleBloodPressure.xml"));

            Guid correlationid = Guid.NewGuid();

            _client.CorrelationId = correlationid;
            BloodPressure bloodPressure = await _client.GetThingAsync <BloodPressure>(_recordId, Guid.NewGuid());

            // ensure that the connection was called with the proper values
            await _connection.Received().ExecuteAsync(
                method: HealthVaultMethods.GetThings,
                methodVersion: 3,
                parameters: Arg.Any <string>(),
                recordId: Arg.Is <Guid>(x => x == _recordId),
                correlationId: correlationid);

            Assert.IsNotNull(bloodPressure);
        }