public async Task CanAccess_ApiKey_SingleCollection_ById_AndView_SinggleMetadataField()
        {
            using (var client = new M2XClient(_masterKey))
            {
                var collectionParameters   = $"{{ \"name\": \"*** PLEASE DELETE ME *** Test Auto Created Collection {DateTime.UtcNow.Ticks}\", \"metadata\": {{ \"{Constants.TestMetadataDefaultFieldName}\": \"{Constants.TestMetadataDefaultFieldValue}\" }} }}";
                var createCollectionResult = await client.CreateCollection(collectionParameters);

                Assert.IsNotNull(createCollectionResult);
                Assert.IsFalse(createCollectionResult.Error);
                Assert.IsFalse(createCollectionResult.ServerError);
                Assert.IsNull(createCollectionResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(createCollectionResult.Raw));

                var collectionData = JsonConvert.DeserializeObject <Collection>(createCollectionResult.Raw);
                var collection     = client.Collection(collectionData.id);

                var result = await collection.MetadataField(Constants.TestMetadataDefaultFieldName);

                Assert.IsNotNull(result);
                Assert.IsFalse(result.Error);
                Assert.IsFalse(result.ServerError);
                Assert.IsNull(result.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                Assert.IsTrue(result.Raw.Length > 6);

                var deleteCollectionResult = await collection.Delete();

                RequestWasProcessedAndReturnedExpectedValue(deleteCollectionResult);
            }
        }
        public async Task CanAccess_MasterApiKey_AndSendCommands()
        {
            try
            {
                using (var client = new M2XClient(_masterKey))
                {
                    var sendCommandParms = new StringBuilder($"{{ ");
                    sendCommandParms.Append($"\"name\": \"PHONE_HOME\"");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"data\": {{ \"server_url\": \"https://m2x.att.com\" }}");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"targets\": {{ \"devices\": [\"{_testDevice.id}\"] }}");
                    sendCommandParms.Append($" }}");

                    var result = await client.SendCommand(sendCommandParms.ToString());

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    Assert.AreEqual(Constants.M2X_Response_Success_Accepted, result.Raw);
                }
            }
            catch (Exception)
            {
                DestroyTestDevice();
                throw;
            }
        }
        public static void InitializeTestSpecs(TestContext testContext)
        {
            _devices          = new Dictionary <string, Device>();
            _testDeviceSerial = $"td-{DateTime.UtcNow.Ticks}";

            using (var client = new M2XClient(_masterKey))
            {
                var createDeviceParms  = $"{{ \"base_device\": \"d781ab7460136af9db496c97172a6e6c\", \"name\": \"{Constants.TestDeviceNamePrefix} {DateTime.UtcNow.Ticks}\", \"description\": \"{Constants.TestDeviceDescription}\", \"serial\": \"{_testDeviceSerial}\", \"visibility\": \"private\" }}";
                var createDeviceResult = client.CreateDevice(createDeviceParms).Result;
                var device             = JsonConvert.DeserializeObject <Device>(createDeviceResult.Raw);
                _devices.Add("primary", device);
                _testDeviceId = device.id;
                var testDevice          = client.Device(device.id);
                var updateTagsParms     = "{ \"tags\": \"test only\" }";
                var resultTags          = testDevice.Update(updateTagsParms).Result;
                var updateLocationParms = $"{{ \"name\": \"Test Device Location\", \"latitude\": {Constants.TestDeviceLatitude}, \"longitude\": {Constants.TestDeviceLongitude} }}";
                var resultLocation      = testDevice.UpdateLocation(updateLocationParms).Result;
                var updateMetadataParms = "{ \"owner\": \"The Testing Guy\" } ";
                var resultMetadata      = testDevice.UpdateMetadata(updateMetadataParms);

                var stream01UpdateParms = $"{{ \"values\": [ {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-10).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": 98.6 }}, {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": 98.7 }} ] }}";
                var stream01            = testDevice.Stream(Constants.TestStreamName001);
                var resultStream01Post  = stream01.PostValues(stream01UpdateParms).Result;
                System.Threading.Thread.Sleep(500);

                var stream02UpdateParms = $"{{ \"values\": [ {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-10).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": \"normal\" }}, {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": \"normal\" }} ] }}";
                var stream02            = testDevice.Stream(Constants.TestStreamName002);
                var resultStream02Post  = stream02.PostValues(stream02UpdateParms).Result;
                System.Threading.Thread.Sleep(500);
            }
        }
Beispiel #4
0
        private static void DestroyTestResources()
        {
            if ((_devices != null && _devices.Any()) || (_distributions != null && _distributions.Any()))
            {
                using (var client = new M2XClient(_masterKey))
                {
                    if (_distributions != null && _distributions.Any())
                    {
                        for (var i = _distributions.Count(); i > 0; i--)
                        {
                            var _distribution = _distributions.ElementAt(i - 1);
                            var distribution  = client.Distribution(_distribution.Value.id);
                            var result        = distribution.Delete().Result;
                            System.Threading.Thread.Sleep(250);
                            _distributions.Remove(_distribution.Key);
                        }
                    }

                    if (_devices != null && _devices.Any())
                    {
                        for (var i = _devices.Count(); i > 0; i--)
                        {
                            var _device = _devices.ElementAt(i - 1);
                            var device  = client.Device(_device.Value.id);
                            var result  = device.Delete().Result;
                            System.Threading.Thread.Sleep(250);
                            _devices.Remove(_device.Key);
                        }
                    }
                }
            }
        }
Beispiel #5
0
        public String getData()
        {
            stream = device.Stream("hasFallen");
            string a = "";

            response = stream.Values(new ATTM2X.Classes.StreamValuesFilter {
                start = M2XClient.DateTimeToString(DateTime.UtcNow.AddMinutes(-3))
            }, M2XStreamValuesFormat.Json).Result;
            var data = response.Json <StreamValues>();

            if (DateTime.Compare(limit, Convert.ToDateTime(data.end)) < 0)
            {
                if (data.values.Length != 0)
                {
                    TimeSpan span = (Convert.ToDateTime(data.values[0].timestamp) - lastFall);
                    if (span.Seconds > 30)
                    {
                        a = data.values[0].value;
                        if (a == "fall")
                        {
                            lastFall = Convert.ToDateTime(data.values[0].timestamp);
                        }
                        System.Console.WriteLine("FALLLL---------------------------------/////////");
                    }
                }
            }
            else
            {
                a = "";
            }

            limit = Convert.ToDateTime(data.end);

            return(a);
        }
        public async Task CanCreate_AndDelete_Collection_WithAll_RequiredParameters()
        {
            using (var client = new M2XClient(_masterKey))
            {
                var collectionParameters = $"{{ \"name\": \"*** PLEASE DELETE ME *** Test Auto Created Collection {DateTime.UtcNow.Ticks}\" }}";
                var result = await client.CreateCollection(collectionParameters);

                Assert.IsNotNull(result);
                Assert.IsFalse(result.Error);
                Assert.IsFalse(result.ServerError);
                Assert.IsNull(result.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));

                var collection = JsonConvert.DeserializeObject <Collection>(result.Raw);
                Assert.IsNotNull(collection);

                var collectionWrapper = client.Collection(collection.id);
                Assert.IsNotNull(collectionWrapper);
                await collectionWrapper.Delete();

                var collectionCheck       = client.Collection(collection.id);
                var collectionCheckResult = await collectionCheck.Details();

                Assert.IsNotNull(collectionCheck);
                Assert.IsTrue(collectionCheckResult.Error);
                Assert.IsFalse(collectionCheckResult.ServerError);
                Assert.IsNull(collectionCheckResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(collectionCheckResult.Raw));
                ProcessCollectionsSearchResult(collectionCheckResult.Raw, false);
            }
        }
Beispiel #7
0
        public void Init()
        {
            this.TestId = Guid.NewGuid().ToString("N");
            this.UtcNow = DateTime.UtcNow;

            this.m2x = new M2XClient(MasterKey);
        }
Beispiel #8
0
        public async Task CanAccess_ApiKey_SingleDistribution_ById_AndUpdate_DistributionMetadata_SingleField()
        {
            if (_accountIsNotPro)
            {
                Assert.Inconclusive("The API key used for this test run is not enabled for Full Access. Please upgrade the account or use an API key that has the necessary permissions.");
                return;
            }

            using (var client = new M2XClient(_masterKey))
            {
                var distribution = client.Distribution(_distributions["primary"].id);

                var updateMetaDataValue  = "The man sitting next to the man...";
                var updateMetaDataParams = $"{{ \"value\": \"{updateMetaDataValue}\" }}";
                var result = await distribution.UpdateMetadataField(Constants.TestMetadataDefaultFieldName, updateMetaDataParams);

                RequestWasProcessedAndReturnedExpectedValue(result);

                var verifyUpdateResult = await distribution.Metadata();

                Assert.IsNotNull(verifyUpdateResult);
                Assert.IsFalse(verifyUpdateResult.Error);
                Assert.IsFalse(verifyUpdateResult.ServerError);
                Assert.IsNull(verifyUpdateResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(verifyUpdateResult.Raw));
                Assert.IsTrue(verifyUpdateResult.Raw.Length > 6);
                Assert.IsTrue(verifyUpdateResult.Raw.ToLowerInvariant().Contains(updateMetaDataValue.ToLowerInvariant()));
            }
        }
Beispiel #9
0
 public void Cleanup()
 {
     if (this.key != null)
     {
         Delete(this.key);
         this.key = null;
     }
     if (this.stream != null)
     {
         Delete(this.stream);
         this.stream = null;
     }
     if (this.device != null)
     {
         Delete(this.device);
         this.device = null;
     }
     if (this.distribution != null)
     {
         Delete(this.distribution);
         this.distribution = null;
     }
     if (this.collection != null)
     {
         Delete(this.collection);
         this.collection = null;
     }
     if (this.m2x != null)
     {
         this.m2x.Dispose();
         this.m2x = null;
     }
 }
 public static void InitializeTestSpecs(TestContext testContext)
 {
     using (var client = new M2XClient(_masterKey))
     {
         var createDeviceParms  = $"{{ \"name\": \"*** PLEASE DELETE ME *** Test Auto Created Device {DateTime.UtcNow.Ticks}\", \"visibility\": \"private\" }}";
         var createDeviceResult = client.CreateDevice(createDeviceParms).Result;
         _testDevice       = JsonConvert.DeserializeObject <Device>(createDeviceResult.Raw);
         _testDeviceExists = _testDevice != null;
     }
 }
Beispiel #11
0
        public static void InitializeTestSpecs(TestContext testContext)
        {
            _devices          = new Dictionary <string, Device>();
            _distributions    = new Dictionary <string, Distribution>();
            _testDeviceSerial = $"td-{DateTime.UtcNow.Ticks}";

            using (var client = new M2XClient(_masterKey))
            {
                var createDeviceParms  = $"{{ \"base_device\": \"d781ab7460136af9db496c97172a6e6c\", \"name\": \"{Constants.TestDeviceNamePrefix} {DateTime.UtcNow.Ticks}\", \"description\": \"{Constants.TestDeviceDescription}\", \"serial\": \"{_testDeviceSerial}\", \"visibility\": \"private\" }}";
                var createDeviceResult = client.CreateDevice(createDeviceParms).Result;
                var device             = JsonConvert.DeserializeObject <Device>(createDeviceResult.Raw);
                _devices.Add("primary", device);
                _testDeviceId = device.id;

                var testDevice      = client.Device(device.id);
                var updateTagsParms = "{ \"tags\": \"test only\" }";
                var resultTags      = testDevice.Update(updateTagsParms).Result;
                for (var i = 0; i < 5; i++)
                {
                    var updateLocationParms = $"{{ \"name\": \"Test Device Location{i + 1}\", \"latitude\": {(Constants.TestDeviceLatitude + i)}, \"longitude\": {(Constants.TestDeviceLongitude + i)} }}";
                    var resultLocation      = testDevice.UpdateLocation(updateLocationParms).Result;
                }
                var updateMetadataParms = $"{{ \"{Constants.TestMetadataDefaultFieldName}\": \"{Constants.TestMetadataDefaultFieldValue}\" }} ";
                var resultMetadata      = testDevice.UpdateMetadata(updateMetadataParms);

                var stream01UpdateParms = $"{{ \"values\": [ {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-10).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": 98.6 }}, {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": 98.7 }} ] }}";
                var stream01            = testDevice.Stream(Constants.TestStreamName001);
                var resultStream01Post  = stream01.PostValues(stream01UpdateParms).Result;
                System.Threading.Thread.Sleep(250);

                var stream02UpdateParms = $"{{ \"values\": [ {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-10).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": \"normal\" }}, {{ \"timestamp\": \"{DateTime.Now.AddSeconds(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")}\", \"value\": \"normal\" }} ] }}";
                var stream02            = testDevice.Stream(Constants.TestStreamName002);
                var resultStream02Post  = stream02.PostValues(stream02UpdateParms).Result;
                System.Threading.Thread.Sleep(250);

                var testDistributionCreateParms  = $"{{ \"name\": \"Test Distribution {DateTime.Now.Ticks}\", \"description\": \"This is just a test!\", \"visibility\": \"private\", \"base_device\": \"{_testDeviceId}\", \"metadata\": {{ \"{Constants.TestMetadataDefaultFieldName}\": \"{Constants.TestMetadataDefaultFieldValue}\" }} }}";
                var testDistributionCreateResult = client.CreateDistribution(testDistributionCreateParms).Result;
                _accountIsNotPro = testDistributionCreateResult.Error;

                if (_accountIsNotPro)
                {
                    return;
                }

                var testDistribution           = JsonConvert.DeserializeObject <Distribution>(testDistributionCreateResult.Raw);
                var distributionAddDeviceParms = $"{{ \"serial\": \"td-{(DateTime.UtcNow.Ticks + 50)}\" }}";
                var distributionDeviceData     = client.Distribution(testDistribution.id).AddDevice(distributionAddDeviceParms).Result;
                var distributionDevice         = JsonConvert.DeserializeObject <Device>(distributionDeviceData.Raw);
                _devices.Add(distributionDevice.serial, distributionDevice);
                _distributions.Add("primary", testDistribution);
                System.Threading.Thread.Sleep(250);
            }
        }
        public async Task CanList_CanAccess_ApiKey_Collections_List()
        {
            using (var client = new M2XClient(_masterKey))
            {
                var result = await client.Collections();

                Assert.IsNotNull(result);
                Assert.IsFalse(result.Error);
                Assert.IsFalse(result.ServerError);
                Assert.IsNull(result.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                ProcessCollectionsSearchResult(result.Raw, false);
            }
        }
 private static void DestroyTestDevice()
 {
     if (_testDeviceExists)
     {
         using (var client = new M2XClient(_masterKey))
         {
             var device = client.Device(_testDevice.id);
             device.Delete();
             System.Threading.Thread.Sleep(500);
             _testDevice       = null;
             _testDeviceExists = false;
         }
     }
 }
        public async Task CanAccess_MasterApiKey_ListOf_CommandsSent_TakeOne_AndView_Details()
        {
            try
            {
                var targetCommandId = string.Empty;
                using (var client = new M2XClient(_masterKey))
                {
                    var retrieveCommandsResult = await client.Commands();

                    Assert.IsNotNull(retrieveCommandsResult);
                    Assert.IsFalse(retrieveCommandsResult.Error);
                    Assert.IsFalse(retrieveCommandsResult.ServerError);
                    Assert.IsNull(retrieveCommandsResult.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(retrieveCommandsResult.Raw));

                    var commandData = JsonConvert.DeserializeObject <ApiResponseForCommandSearch>(retrieveCommandsResult.Raw);
                    if (!commandData.commands.Any())
                    {
                        Assert.Fail("There are no commands to view. Please send one using the appropriate test or create one manually before trying again.");
                    }
                    targetCommandId = commandData.commands.First().id;
                }


                using (var client = new M2XClient(_masterKey))
                {
                    var result = await client.CommandDetails(targetCommandId);

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));

                    var commandDetail = JsonConvert.DeserializeObject <ApiResponseForCommandDetail>(result.Raw);
                    Assert.IsNotNull(commandDetail);
                    Assert.IsNotNull(commandDetail.data);
                    Assert.IsNotNull(commandDetail.deliveries);
                    Assert.AreNotEqual(default(DateTime), commandDetail.sent_at);
                }
            }
            catch (Exception)
            {
                DestroyTestDevice();
                throw;
            }
        }
 private static void DestroyTestDevices()
 {
     if (_devices != null && _devices.Any())
     {
         for (var i = _devices.Count(); i > 0; i--)
         {
             var _device = _devices.ElementAt(i - 1);
             using (var client = new M2XClient(_masterKey))
             {
                 var device = client.Device(_device.Value.id);
                 device.Delete();
                 System.Threading.Thread.Sleep(500);
                 _devices.Remove(_device.Key);
             }
         }
     }
 }
Beispiel #16
0
        public async Task CanAccess_ApiKey_Distributions()
        {
            if (_accountIsNotPro)
            {
                Assert.Inconclusive("The API key used for this test run is not enabled for Full Access. Please upgrade the account or use an API key that has the necessary permissions.");
                return;
            }

            using (var client = new M2XClient(_masterKey))
            {
                var result = await client.Distributions();

                Assert.IsNotNull(result);
                Assert.IsFalse(result.Error);
                Assert.IsFalse(result.ServerError);
                Assert.IsNull(result.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                ProcessDistributionSearchResult(result.Raw);
            }
        }
Beispiel #17
0
        public async Task CanAccess_ApiKey_SingleDistribution_ById_AndUpdate_DistributionMetadata()
        {
            if (_accountIsNotPro)
            {
                Assert.Inconclusive("The API key used for this test run is not enabled for Full Access. Please upgrade the account or use an API key that has the necessary permissions.");
                return;
            }

            using (var client = new M2XClient(_masterKey))
            {
                var distributionName         = $"*** PLEASE DELETE ME *** Test Auto Created Distribution {DateTime.UtcNow.Ticks}";
                var distributionParameters   = $"{{ \"name\": \"{distributionName}\", \"visibility\": \"private\", \"metadata\": {{ \"{Constants.TestMetadataDefaultFieldName}\": \"{Constants.TestMetadataDefaultFieldValue}\" }} }}";
                var createDistributionResult = await client.CreateDistribution(distributionParameters);

                Assert.IsNotNull(createDistributionResult);
                Assert.IsFalse(createDistributionResult.Error);
                Assert.IsFalse(createDistributionResult.ServerError);
                Assert.IsNull(createDistributionResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(createDistributionResult.Raw));

                var distributionData = JsonConvert.DeserializeObject <Distribution>(createDistributionResult.Raw);
                var distribution     = client.Distribution(distributionData.id);
                _distributions.Add(distributionName, distributionData);

                var updateMetaDataValue  = "The man sitting next to the man...";
                var updateMetaDataParams = $"{{ \"owner\": \"{updateMetaDataValue}\" }}";
                var result = await distribution.UpdateMetadata(updateMetaDataParams);

                RequestWasProcessedAndReturnedExpectedValue(result);

                var verifyUpdateResult = await distribution.Metadata();

                Assert.IsNotNull(verifyUpdateResult);
                Assert.IsFalse(verifyUpdateResult.Error);
                Assert.IsFalse(verifyUpdateResult.ServerError);
                Assert.IsNull(verifyUpdateResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(verifyUpdateResult.Raw));
                Assert.IsTrue(verifyUpdateResult.Raw.Length > 6);
                Assert.IsTrue(verifyUpdateResult.Raw.ToLowerInvariant().Contains(updateMetaDataValue.ToLowerInvariant()));
            }
        }
        public async Task CanAccess_MasterApiKey_ListOf_CommandsSent_NoFilters()
        {
            try
            {
                using (var client = new M2XClient(_masterKey))
                {
                    var result = await client.Commands();

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    ProcessCommandSearchResult(result.Raw, null);
                }
            }
            catch (Exception)
            {
                DestroyTestDevice();
                throw;
            }
        }
Beispiel #19
0
        public async Task CanAccess_ApiKey_SingleDistribution_ById_AndView_SingleMetadataField()
        {
            if (_accountIsNotPro)
            {
                Assert.Inconclusive("The API key used for this test run is not enabled for Full Access. Please upgrade the account or use an API key that has the necessary permissions.");
                return;
            }

            using (var client = new M2XClient(_masterKey))
            {
                var distribution = client.Distribution(_distributions["primary"].id);

                var result = await distribution.MetadataField(Constants.TestMetadataDefaultFieldName);

                Assert.IsNotNull(result);
                Assert.IsFalse(result.Error);
                Assert.IsFalse(result.ServerError);
                Assert.IsNull(result.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                Assert.IsTrue(result.Raw.Length > 6);
            }
        }
        public async Task CanAccess_ApiKey_SingleCollection_ById_AndUpdate_CollectionMetadata()
        {
            using (var client = new M2XClient(_masterKey))
            {
                var collectionParameters   = $"{{ \"name\": \"*** PLEASE DELETE ME *** Test Auto Created Collection {DateTime.UtcNow.Ticks}\", \"metadata\": {{ \"{Constants.TestMetadataDefaultFieldName}\": \"{Constants.TestMetadataDefaultFieldValue}\" }} }}";
                var createCollectionResult = await client.CreateCollection(collectionParameters);

                Assert.IsNotNull(createCollectionResult);
                Assert.IsFalse(createCollectionResult.Error);
                Assert.IsFalse(createCollectionResult.ServerError);
                Assert.IsNull(createCollectionResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(createCollectionResult.Raw));

                var collectionData = JsonConvert.DeserializeObject <Collection>(createCollectionResult.Raw);
                var collection     = client.Collection(collectionData.id);

                var updateMetaDataValue  = "The man sitting next to the man...";
                var updateMetaDataParams = $"{{ \"owner\": \"{updateMetaDataValue}\" }}";
                var result = await collection.UpdateMetadata(updateMetaDataParams);

                RequestWasProcessedAndReturnedExpectedValue(result);

                var verifyUpdateResult = await collection.Metadata();

                Assert.IsNotNull(verifyUpdateResult);
                Assert.IsFalse(verifyUpdateResult.Error);
                Assert.IsFalse(verifyUpdateResult.ServerError);
                Assert.IsNull(verifyUpdateResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(verifyUpdateResult.Raw));
                Assert.IsTrue(verifyUpdateResult.Raw.Length > 6);
                Assert.IsTrue(verifyUpdateResult.Raw.ToLowerInvariant().Contains(updateMetaDataValue.ToLowerInvariant()));


                var deleteCollectionResult = await collection.Delete();

                RequestWasProcessedAndReturnedExpectedValue(deleteCollectionResult);
            }
        }
Beispiel #21
0
        public void CommandsApiTest()
        {
            response = m2x.CreateDevice(new DeviceParams
            {
                name       = "TestDevice-" + this.TestId,
                visibility = M2XVisibility.Private,
            }).Result;
            Assert.AreEqual(HttpStatusCode.Created, response.Status, response.Raw);
            var deviceDetails = response.Json <DeviceDetails>();

            Assert.IsNotNull(deviceDetails.id);
            this.device = m2x.Device(deviceDetails.id);
            Thread.Sleep(1000);

            string commandName = "TestCommand-" + this.TestId;

            response = m2x.SendCommand(new SendCommandParams
            {
                name    = commandName,
                targets = new CommandTargets {
                    devices = new string[] { deviceDetails.id }
                },
            }).Result;
            Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);
            Thread.Sleep(1000);

            response = m2x.Commands(new CommandParams {
                name = commandName
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var commands = response.Json <CommandList <CommandDetails> >();

            Assert.IsNotNull(commands, response.Raw);
            Assert.IsNotNull(commands.commands, response.Raw);
            Assert.AreEqual(1, commands.commands.Length, response.Raw);
            Assert.AreEqual(commandName, commands.commands[0].name, response.Raw);
            string commandId = commands.commands[0].id;

            Assert.IsNotNull(commandId, response.Raw);

            response = m2x.CommandDetails(commandId).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var command = response.Json <CommandDetails>();

            Assert.IsNotNull(command, response.Raw);
            Assert.AreEqual(commandName, command.name, response.Raw);

            response = m2x.Keys(new KeyListParams {
                device = deviceDetails.id
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var keys = response.Json <KeyList>();

            Assert.IsNotNull(keys, response.Raw);
            Assert.IsNotNull(keys.keys, response.Raw);
            Assert.AreEqual(1, keys.keys.Length, response.Raw);
            Assert.IsTrue(keys.keys[0].device.Contains(deviceDetails.id), response.Raw);
            string key = keys.keys[0].key;

            Assert.AreEqual(deviceDetails.key, key, response.Raw);
            Assert.IsNotNull(key, response.Raw);

            using (var deviceClient = new M2XClient(deviceDetails.key))
            {
                var device_ = deviceClient.Device(deviceDetails.id);

                response = device_.Commands(new CommandParams {
                    status = M2XCommandStatus.Sent
                }).Result;
                Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
                commands = response.Json <CommandList <CommandDetails> >();
                Assert.IsNotNull(commands, response.Raw);
                Assert.IsNotNull(commands.commands, response.Raw);
                Assert.AreEqual(1, commands.commands.Length, response.Raw);
                Assert.AreEqual(commandName, commands.commands[0].name, response.Raw);
                Assert.AreEqual(commandId, commands.commands[0].id, response.Raw);
                Assert.AreEqual(M2XCommandStatus.Sent, commands.commands[0].status, response.Raw);

                response = device_.CommandDetails(commandId).Result;
                Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
                command = response.Json <CommandDetails>();
                Assert.IsNotNull(command, response.Raw);
                Assert.AreEqual(commandName, command.name, response.Raw);
                Assert.AreEqual(M2XCommandStatus.Sent, command.status, response.Raw);

                response = device_.ProcessCommand(commandId).Result;
                Assert.AreEqual(HttpStatusCode.NoContent, response.Status, response.Raw);
                Thread.Sleep(1000);
                response = device_.CommandDetails(commandId).Result;
                Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
                command = response.Json <CommandDetails>();
                Assert.IsNotNull(command, response.Raw);
                Assert.AreEqual(commandName, command.name, response.Raw);
                Assert.AreEqual(M2XCommandStatus.Processed, command.status, response.Raw);

                commandName = "TestCommand2-" + this.TestId;
                response    = m2x.SendCommand(new SendCommandParams
                {
                    name    = commandName,
                    targets = new CommandTargets {
                        devices = new string[] { deviceDetails.id }
                    },
                }).Result;
                Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);
                Thread.Sleep(1000);

                response = device_.Commands(new CommandParams {
                    status = M2XCommandStatus.Sent
                }).Result;
                Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
                commands = response.Json <CommandList <CommandDetails> >();
                Assert.IsNotNull(commands, response.Raw);
                Assert.IsNotNull(commands.commands, response.Raw);
                Assert.AreEqual(1, commands.commands.Length, response.Raw);
                Assert.AreEqual(commandName, commands.commands[0].name, response.Raw);
                commandId = commands.commands[0].id;

                response = device_.RejectCommand(commandId).Result;
                Assert.AreEqual(HttpStatusCode.NoContent, response.Status, response.Raw);
                Thread.Sleep(1000);
                response = device_.CommandDetails(commandId).Result;
                Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
                command = response.Json <CommandDetails>();
                Assert.IsNotNull(command, response.Raw);
                Assert.AreEqual(commandName, command.name, response.Raw);
                Assert.AreEqual(M2XCommandStatus.Rejected, command.status, response.Raw);
            }
        }
Beispiel #22
0
        public void DeviceAPITest()
        {
            // device

            response = m2x.DeviceTags().Result;
            Assert.IsNotNull(m2x.LastResponse);
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            Assert.IsTrue(response.Success);
            Assert.IsFalse(response.Error);
            Assert.IsNotNull(response.Raw);

            response = m2x.DeviceCatalog(new DeviceListParams {
                page = 1, limit = 10, sort = M2XDeviceSortOrder.Name, dir = M2XSortDirection.Asc
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var deviceList = response.Json <DeviceList>();

            Assert.IsNotNull(deviceList.devices);
            Assert.IsTrue(deviceList.devices.Length > 0);

            DeviceDetails deviceDetails = deviceList.devices.FirstOrDefault(d => d.location != null && d.location.latitude.HasValue && d.location.longitude.HasValue);

            Assert.IsNotNull(deviceDetails);
            response = m2x.DeviceCatalogSearch(null, new DeviceSearchBodyParamsBase
            {
                location = new LocationFilter
                {
                    within_circle = new WithinCircleFilter
                    {
                        center = new LocationPointParams
                        {
                            latitude  = deviceDetails.location.latitude.Value,
                            longitude = deviceDetails.location.longitude.Value,
                        },
                        radius = new RadiusParams {
                            km = 10
                        },
                    },
                },
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            deviceList = response.Json <DeviceList>();
            Assert.IsNotNull(deviceList.devices);
            // TODO: Assert.IsTrue(deviceList.devices.Length > 0);

            response = m2x.CreateDevice(new DeviceParams
            {
                name       = "TestDevice-" + this.TestId,
                visibility = M2XVisibility.Private,
            }).Result;
            Assert.AreEqual(HttpStatusCode.Created, response.Status, response.Raw);
            deviceDetails = response.Json <DeviceDetails>();
            Assert.IsNotNull(deviceDetails.id);
            this.device = m2x.Device(deviceDetails.id);
            Assert.AreEqual(M2XVisibility.Private, deviceDetails.visibility);

            Thread.Sleep(1000);

            response = device.Details().Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            deviceDetails = response.Json <DeviceDetails>();
            Assert.AreEqual(M2XStatus.Enabled, deviceDetails.status);

            response = device.Update(new DeviceParams
            {
                name        = "TestDevice-" + this.TestId,
                visibility  = M2XVisibility.Private,
                description = "test",
            }).Result;
            Assert.AreEqual(HttpStatusCode.NoContent, response.Status, response.Raw);
            response = device.Details().Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            deviceDetails = response.Json <DeviceDetails>();
            Assert.AreEqual("test", deviceDetails.description);

            response = device.UpdateLocation(new LocationParams
            {
                name      = "Test Location",
                latitude  = 12,
                longitude = -34,
            }).Result;
            Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);

            Thread.Sleep(2000);

            response = device.Location().Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var location = response.Json <LocationDetails>();

            Assert.AreEqual("Test Location", location.name);

            response = m2x.Devices(new { visibility = M2XVisibility.Private }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            deviceList = response.Json <DeviceList>();
            Assert.IsNotNull(deviceList.devices);
            Assert.IsTrue(deviceList.devices.Length > 0);

            response = m2x.SearchDevices(new DeviceSearchParams {
                visibility = M2XVisibility.Private
            }, new DeviceSearchBodyParamsBase
            {
                location = new LocationFilter
                {
                    within_circle = new WithinCircleFilter
                    {
                        center = new LocationPointParams
                        {
                            latitude  = location.latitude.Value,
                            longitude = location.longitude.Value,
                        },
                        radius = new RadiusParams {
                            km = 10
                        },
                    },
                },
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            deviceList = response.Json <DeviceList>();
            Assert.IsNotNull(deviceList.devices);
            Assert.IsTrue(deviceList.devices.Length > 0);

            response = device.Log().Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var requestList = response.Json <RequestList>();

            Assert.IsNotNull(requestList.requests);
            Assert.IsTrue(requestList.requests.Length > 0);

            // stream

            this.stream = device.Stream("testdevicestream");
            response    = stream.Update(new StreamParams
            {
                type = M2XStreamType.Numeric,
                unit = new StreamUnit {
                    label = "points", symbol = "pt"
                },
            }).Result;
            Assert.AreEqual(HttpStatusCode.Created, response.Status, response.Raw);

            Thread.Sleep(1000);

            response = device.Streams().Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var streamList = response.Json <StreamList>();

            Assert.IsNotNull(streamList.streams);
            Assert.AreEqual(1, streamList.streams.Length);
            Assert.AreEqual(stream.StreamName, streamList.streams[0].name);

            response = stream.UpdateValue(new StreamValue {
                value = "10"
            }).Result;
            Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);

            Thread.Sleep(1000);

            response = stream.Details().Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var streamDetails = response.Json <StreamDetails>();

            Assert.AreEqual("10", streamDetails.value);

            response = stream.Values(new StreamValuesFilter {
                start = M2XClient.DateTimeToString(this.UtcNow.AddHours(-1))
            }, M2XStreamValuesFormat.Json).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var streamValues = response.Json <StreamValues>();

            Assert.IsNotNull(streamValues.values);
            Assert.AreEqual(1, streamValues.values.Length);

            response = stream.UpdateValue(new StreamValue {
                value = "20"
            }).Result;
            Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);

            Thread.Sleep(1500);

            response = stream.Sampling(new StreamSamplingParams {
                type = M2XSamplingType.Sum, interval = 100
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            streamValues = response.Json <StreamValues>();
            Assert.IsNotNull(streamValues.values);
            Assert.AreEqual(1, streamValues.values.Length);
            Assert.AreEqual("30.0", streamValues.values[0].value);

            response = stream.Stats().Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var streamStats = response.Json <StreamStatsInfo>();

            Assert.IsNotNull(streamStats.stats);
            Assert.AreEqual(2, streamStats.stats.count);
            Assert.AreEqual(15.0, streamStats.stats.avg);

            string from = M2XClient.DateTimeToString(this.UtcNow.AddMinutes(-2));
            string end  = M2XClient.DateTimeToString(this.UtcNow.AddMinutes(-1));

            response = stream.PostValues(new StreamValues
            {
                values = new StreamValue[]
                {
                    new StreamValue {
                        timestamp = from, value = "1",
                    },
                    new StreamValue {
                        timestamp = end, value = "2",
                    },
                }
            }).Result;
            Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);

            response = stream.DeleteValues(new DeleteValuesParams {
                from = from, end = end
            }).Result;
            Assert.AreEqual(HttpStatusCode.NoContent, response.Status, response.Raw);

            // values

            response = device.PostUpdate(new TestDeviceValue
            {
                timestamp = M2XClient.DateTimeToString(this.UtcNow.AddMinutes(-3)),
                values    = new TestDeviceStreamValue {
                    testdevicestream = 3
                },
            }).Result;
            Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);

            response = device.PostUpdates(new TestDeviceValues
            {
                values = new TestDeviceStreamValues
                {
                    testdevicestream = new StreamValue[]
                    {
                        new StreamValue {
                            timestamp = from, value = "1",
                        },
                        new StreamValue {
                            timestamp = end, value = "2",
                        },
                    },
                },
            }).Result;
            Assert.AreEqual(HttpStatusCode.Accepted, response.Status, response.Raw);

            Thread.Sleep(1000);

            response = device.Values(new DeviceValuesFilter {
                streams = "testdevicestream"
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            var values = response.Json <DeviceValueList <TestDeviceValue> >();

            Assert.IsNotNull(values);
            Assert.IsNotNull(values.values);
            Assert.IsTrue(values.values.Length >= 3);
            int count = values.values.Length;

            response = device.SearchValues(new DeviceValuesSearchParams <TestDeviceConditions>
            {
                start      = values.values.Min(v => v.timestamp),
                end        = values.values.Max(v => v.timestamp),
                streams    = new string[] { "testdevicestream" },
                conditions = new TestDeviceConditions {
                    testdevicestream = new ValueCondition {
                        gt = 1
                    }
                },
            }).Result;
            Assert.AreEqual(HttpStatusCode.OK, response.Status, response.Raw);
            values = response.Json <DeviceValueList <TestDeviceValue> >();
            Assert.IsNotNull(values);
            Assert.IsNotNull(values.values);
            Assert.IsTrue(values.values.Length > 0);
            Assert.IsTrue(values.values.Length < count);
        }
        public async Task CanAccess_MasterApiKey_AndSendCommands_ToSingleDevice_AndDevice_MarksCommand_AsRejected()
        {
            try
            {
                var commandName = "PHONE_HOME";
                using (var client = new M2XClient(_masterKey))
                {
                    var sendCommandParms = new StringBuilder($"{{ ");
                    sendCommandParms.Append($"\"name\": \"{commandName}\"");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"data\": {{ \"server_url\": \"https://m2x.att.com\" }}");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"targets\": {{ \"devices\": [\"{_testDevice.id}\"] }}");
                    sendCommandParms.Append($" }}");

                    var result = await client.SendCommand(sendCommandParms.ToString());

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    Assert.AreEqual(Constants.M2X_Response_Success_Accepted, result.Raw);
                }

                System.Threading.Thread.Sleep(1000);
                var targetCommandId = string.Empty;
                using (var client = new M2XClient(_masterKey))
                {
                    var device = client.Device(_testDevice.id);
                    var result = await device.Commands();

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    var commandData = JsonConvert.DeserializeObject <ApiResponseForCommandSearch>(result.Raw);
                    Assert.IsNotNull(commandData);
                    targetCommandId = commandData.commands.All(a => a.status_counts == null)
                                                ? commandData.commands.First().id
                                                : commandData.commands.First(f => f.status_counts.processed == 0 && f.status_counts.rejected == 0 && f.status_counts.pending > 0).id;
                }

                System.Threading.Thread.Sleep(500);
                using (var client = new M2XClient(_masterKey))
                {
                    var device       = client.Device(_testDevice.id);
                    var processParms = $"{{ \"reason\": \"Because I Can!\" }}";
                    var result       = await device.RejectCommand(targetCommandId, processParms);

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsTrue(string.IsNullOrWhiteSpace(result.Raw));
                }

                System.Threading.Thread.Sleep(500);
                using (var client = new M2XClient(_masterKey))
                {
                    var result = await client.Commands();

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    ProcessCommandSearchResultFindTargetCommandAndCheckStatus(result.Raw, _testDevice.id, targetCommandId, "rejected");
                }
            }
            catch (Exception ex)
            {
                DestroyTestDevice();
                throw;
            }
        }
        public async Task CanAccess_MasterApiKey_AndSendCommand_ToSingleDevice_ThenList_CommandsSent_WithFilters()
        {
            try
            {
                var commandName = "PHONE_HOME";
                using (var client = new M2XClient(_masterKey))
                {
                    var sendCommandParms = new StringBuilder($"{{ ");
                    sendCommandParms.Append($"\"name\": \"{commandName}\"");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"data\": {{ \"server_url\": \"https://m2x.att.com\" }}");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"targets\": {{ \"devices\": [\"{_testDevice.id}\"] }}");
                    sendCommandParms.Append($" }}");

                    var result = await client.SendCommand(sendCommandParms.ToString());

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    Assert.AreEqual(Constants.M2X_Response_Success_Accepted, result.Raw);
                }

                System.Threading.Thread.Sleep(1000);
                using (var client = new M2XClient(_masterKey))
                {
                    var device = client.Device(_testDevice.id);
                    foreach (var filter in new[] { "limit", "page", "dir|desc", "dir|asc", "start", "end", "name", "status|pending", "status|processed", "status|rejected" })
                    {
                        M2XResponse result = null;
                        switch (filter)
                        {
                        case "limit":
                            result = await device.Commands(new { limit = 2 });

                            break;

                        case "page":
                            result = await device.Commands(new { page = 1 });

                            break;

                        case "dir|desc":
                            result = await device.Commands(new { dir = "desc" });

                            break;

                        case "dir|asc":
                            result = await device.Commands(new { dir = "asc" });

                            break;

                        case "start":
                            result = await device.Commands(new { start = DateTime.UtcNow.AddMinutes(-60).ToString(Constants.ISO8601_DateStartFormat) });

                            break;

                        case "end":
                            result = await device.Commands(new { end = DateTime.UtcNow.AddMinutes(-10).ToString(Constants.ISO8601_DateStartFormat) });

                            break;

                        case "name":
                            result = await device.Commands(new { name = "PHONE_HOME" });

                            break;

                        case "status|pending":
                            result = await device.Commands(new { status = "pending" });

                            break;

                        case "status|processed":
                            result = await device.Commands(new { status = "processed" });

                            break;

                        case "status|rejected":
                            result = await device.Commands(new { status = "rejected" });

                            break;
                        }

                        Assert.IsNotNull(result);
                        Assert.IsFalse(result.Error);
                        Assert.IsFalse(result.ServerError);
                        Assert.IsNull(result.WebError);
                        Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                        ProcessCommandSearchResult(result.Raw, null);
                    }
                }
            }
            catch (Exception ex)
            {
                DestroyTestDevice();
                throw;
            }
        }
Beispiel #25
0
        public async Task CanSearch_ApiKey_Distributions_ByAllowed_GETParameters()
        {
            if (_accountIsNotPro)
            {
                Assert.Inconclusive("The API key used for this test run is not enabled for Full Access. Please upgrade the account or use an API key that has the necessary permissions.");
                return;
            }

            using (var client = new M2XClient(_masterKey))
            {
                foreach (var searchType in new object[] { null, "q1", "q2", "page", "limit", "tags", "modified_since", "unmodified_since", "visibility" })
                {
                    object searchParams = null;
                    if (searchType != null)
                    {
                        switch (searchType.ToString())
                        {
                        case "q1":
                            searchParams = new { q = Constants.TestDeviceNamePrefix };
                            break;

                        case "q2":
                            searchParams = new { q = Constants.TestDeviceDescription };
                            break;

                        case "page":
                            searchParams = new { page = 1 };
                            break;

                        case "limit":
                            searchParams = new { limit = 2 };
                            break;

                        case "tags":
                            searchParams = new { tags = "test only" };
                            break;

                        case "modified_since":
                            searchParams = new { modified_since = $"{DateTime.Now.AddHours(-1).ToString(Constants.ISO8601_DateStartFormat)}" };
                            break;

                        case "unmodified_since":
                            searchParams = new { unmodified_since = $"{DateTime.Now.AddHours(-1).ToString(Constants.ISO8601_DateStartFormat)}" };
                            break;

                        case "visibility":
                            searchParams = new { visibility = "private" };
                            break;
                        }
                    }

                    var result = await client.SearchDistributions(searchParams);

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    ProcessDistributionSearchResult(result.Raw, true);
                }
            }
        }
        public async Task CanAccess_MasterApiKey_ListOf_CommandsSent_WithFilters()
        {
            try
            {
                using (var client = new M2XClient(_masterKey))
                {
                    foreach (var filter in new[] { "limit", "page", "dir|desc", "dir|asc", "start", "end", "name" })
                    {
                        M2XResponse result = null;
                        switch (filter)
                        {
                        case "limit":
                            result = await client.Commands(new { limit = 2 });

                            break;

                        case "page":
                            result = await client.Commands(new { page = 1 });

                            break;

                        case "dir|desc":
                            result = await client.Commands(new { dir = "desc" });

                            break;

                        case "dir|asc":
                            result = await client.Commands(new { dir = "asc" });

                            break;

                        case "start":
                            result = await client.Commands(new { start = DateTime.UtcNow.AddMinutes(-60).ToString(Constants.ISO8601_DateStartFormat) });

                            break;

                        case "end":
                            result = await client.Commands(new { end = DateTime.UtcNow.AddMinutes(-10).ToString(Constants.ISO8601_DateStartFormat) });

                            break;

                        case "name":
                            result = await client.Commands(new { name = "PHONE_HOME" });

                            break;
                        }

                        Assert.IsNotNull(result);
                        Assert.IsFalse(result.Error);
                        Assert.IsFalse(result.ServerError);
                        Assert.IsNull(result.WebError);
                        Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                        ProcessCommandSearchResult(result.Raw, null);
                    }
                }
            }
            catch (Exception)
            {
                DestroyTestDevice();
                throw;
            }
        }
        public async Task CanCreate_Collection_And_PrivateDevice_ThenAdd_DeviceToCollection_TheRemove_DeviceFromCollection_AndDelete_Both()
        {
            using (var client = new M2XClient(_masterKey))
            {
                var collectionParameters   = $"{{ \"name\": \"*** PLEASE DELETE ME *** Test Auto Created Collection {DateTime.UtcNow.Ticks}\" }}";
                var createCollectionResult = await client.CreateCollection(collectionParameters);

                Assert.IsNotNull(createCollectionResult);
                Assert.IsFalse(createCollectionResult.Error);
                Assert.IsFalse(createCollectionResult.ServerError);
                Assert.IsNull(createCollectionResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(createCollectionResult.Raw));

                var collection = JsonConvert.DeserializeObject <Collection>(createCollectionResult.Raw);
                Assert.IsNotNull(collection);

                var collectionWrapper = client.Collection(collection.id);
                Assert.IsNotNull(collectionWrapper);

                var deviceParameters = $"{{ \"name\": \"*** PLEASE DELETE ME *** Test Auto Created Device {DateTime.UtcNow.Ticks}\", \"visibility\": \"private\" }}";
                var result           = await client.CreateDevice(deviceParameters);

                Assert.IsNotNull(result);
                Assert.IsFalse(result.Error);
                Assert.IsFalse(result.ServerError);
                Assert.IsNull(result.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));

                var device = JsonConvert.DeserializeObject <Device>(result.Raw);
                Assert.IsNotNull(device);

                var addCollectionDeviceResult = await collectionWrapper.AddDevice(device.id);

                Assert.IsNotNull(addCollectionDeviceResult);
                Assert.IsTrue(string.IsNullOrWhiteSpace(addCollectionDeviceResult.Raw));


                var checkCollectionDevices0 = await collectionWrapper.Details();

                Assert.IsNotNull(checkCollectionDevices0);
                Assert.IsFalse(string.IsNullOrWhiteSpace(checkCollectionDevices0.Raw));
                var checkCollection0 = JsonConvert.DeserializeObject <Collection>(checkCollectionDevices0.Raw);
                Assert.IsNotNull(checkCollection0);
                Assert.IsTrue(checkCollection0.devices > 0);

                var removeCollectionDeviceResult = await collectionWrapper.RemoveDevice(device.id);

                Assert.IsNotNull(removeCollectionDeviceResult);
                Assert.IsTrue(string.IsNullOrWhiteSpace(removeCollectionDeviceResult.Raw));


                var checkCollectionDevices1 = await collectionWrapper.Details();

                Assert.IsNotNull(checkCollectionDevices1);
                Assert.IsFalse(string.IsNullOrWhiteSpace(checkCollectionDevices1.Raw));
                var checkCollection1 = JsonConvert.DeserializeObject <Collection>(checkCollectionDevices1.Raw);
                Assert.IsNotNull(checkCollection1);
                Assert.IsTrue(checkCollection1.devices == 0);

                var deviceWrapper = client.Device(device.id, device.serial != null ? device.serial.ToString() : null);
                Assert.IsNotNull(deviceWrapper);
                await deviceWrapper.Delete();

                var devicesCheck = await client.SearchDevices(new { ids = device.id });

                Assert.IsNotNull(devicesCheck);
                Assert.IsFalse(devicesCheck.Error);
                Assert.IsFalse(devicesCheck.ServerError);
                Assert.IsNull(devicesCheck.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(devicesCheck.Raw));
                ProcessDeviceSearchResult(devicesCheck.Raw, false);

                await collectionWrapper.Delete();

                var collectionCheck       = client.Collection(collection.id);
                var collectionCheckResult = await collectionCheck.Details();

                Assert.IsNotNull(collectionCheck);
                Assert.IsTrue(collectionCheckResult.Error);
                Assert.IsFalse(collectionCheckResult.ServerError);
                Assert.IsNull(collectionCheckResult.WebError);
                Assert.IsFalse(string.IsNullOrWhiteSpace(collectionCheckResult.Raw));
                ProcessCollectionsSearchResult(collectionCheckResult.Raw, false);
            }
        }
        public async Task CanAccess_MasterApiKey_AndSendCommands_ToSingleDevice_AndView_Single_DeviceCommand()
        {
            try
            {
                var commandName = "PHONE_HOME";
                using (var client = new M2XClient(_masterKey))
                {
                    var sendCommandParms = new StringBuilder($"{{ ");
                    sendCommandParms.Append($"\"name\": \"{commandName}\"");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"data\": {{ \"server_url\": \"https://m2x.att.com\" }}");
                    sendCommandParms.Append($", ");
                    sendCommandParms.Append($"\"targets\": {{ \"devices\": [\"{_testDevice.id}\"] }}");
                    sendCommandParms.Append($" }}");

                    var result = await client.SendCommand(sendCommandParms.ToString());

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    Assert.AreEqual(Constants.M2X_Response_Success_Accepted, result.Raw);
                }

                System.Threading.Thread.Sleep(500);
                var targetCommandId = string.Empty;
                using (var client = new M2XClient(_masterKey))
                {
                    var device = client.Device(_testDevice.id);
                    var result = await device.Commands();

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));
                    var commandData = JsonConvert.DeserializeObject <ApiResponseForCommandSearch>(result.Raw);
                    Assert.IsNotNull(commandData);
                    targetCommandId = commandData.commands.First().id;
                }

                System.Threading.Thread.Sleep(500);
                using (var client = new M2XClient(_masterKey))
                {
                    var device = client.Device(_testDevice.id);
                    var result = await device.CommandDetails(targetCommandId);

                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Error);
                    Assert.IsFalse(result.ServerError);
                    Assert.IsNull(result.WebError);
                    Assert.IsFalse(string.IsNullOrWhiteSpace(result.Raw));

                    var commandDetail = JsonConvert.DeserializeObject <ApiResponseForCommandDetail>(result.Raw);
                    Assert.IsNotNull(commandDetail);
                    Assert.IsNotNull(commandDetail.data);
                    Assert.AreNotEqual(default(DateTime), commandDetail.sent_at);
                    Assert.AreEqual(commandName, commandDetail.name);
                }
            }
            catch (Exception ex)
            {
                DestroyTestDevice();
                throw;
            }
        }