public void testDoubleQuoteJsonValue() { LeafEvent[] argsjsonexp; argsjsonexp = new LeafEvent[] { new LeafEvent("a", "2 3", true) }; testJsonExplorationParameterised("{ a:\"2 3\" }", 1, 1, 1, argsjsonexp); }
public static async Task EventGridProcess([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log) { log.LogInformation("LeafDeviceCloudEventGrid function processing Event Grid trigger."); log.LogInformation(eventGridEvent.Data.ToString()); iotHubConnectionString = System.Environment.GetEnvironmentVariable("iotHubConnectionString", EnvironmentVariableTarget.Process); dynamic data = JsonConvert.DeserializeObject(eventGridEvent.Data.ToString()); //Note: we assume a JSON payload in the body, 'UTF-8' Encoded AND 'application/json' content type. Otherwise body will be base64 encoded LeafEvent deviceEvent = JsonConvert.DeserializeObject <LeafEvent>(data.body.ToString()); registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); log.LogInformation($"DeviceId: {deviceEvent.LeafDeviceId}"); log.LogInformation($"Parent device id: {deviceEvent.EdgeDeviceId}"); DmCallback callbackResult = new DmCallback(); callbackResult.DeviceId = deviceEvent.LeafDeviceId; switch (deviceEvent.Operation) { case LeafEvent.Operations.create: //check if device is whitelisted string storageConnection = System.Environment.GetEnvironmentVariable("WhitelistStorageConnection", EnvironmentVariableTarget.Process); string container = System.Environment.GetEnvironmentVariable("WhitelistContainerName", EnvironmentVariableTarget.Process); string filename = System.Environment.GetEnvironmentVariable("WhitelistFilename", EnvironmentVariableTarget.Process); bool isValid = await CheckWhiteListDeviceId(storageConnection, container, filename, deviceEvent.LeafDeviceId); if (isValid) { var parentDevice = await registryManager.GetDeviceAsync(deviceEvent.EdgeDeviceId); var parentModule = await registryManager.GetModuleAsync(deviceEvent.EdgeDeviceId, deviceEvent.EdgeModuleId); if (parentDevice == null || parentModule == null) { log.LogError("Error in event grid processing, either module or parent device could not be loaded. Exiting function."); break; } else { //Get module key to be used as master string deviceSymmetricKey = ComputeDerivedSymmetricKey( Convert.FromBase64String(parentModule.Authentication.SymmetricKey.PrimaryKey), deviceEvent.LeafDeviceId); string deviceSecondaryKey = ComputeDerivedSymmetricKey( Convert.FromBase64String(parentModule.Authentication.SymmetricKey.SecondaryKey), deviceEvent.LeafDeviceId); //create new device in registry Device newDevice = new Device(deviceEvent.LeafDeviceId) { Authentication = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = deviceSymmetricKey, SecondaryKey = deviceSecondaryKey } }, Scope = parentDevice.Scope }; Device leafDevice; try { leafDevice = await registryManager.AddDeviceAsync(newDevice); callbackResult.ResultCode = 200; callbackResult.ResultDescriptionn = "Device successfully created in IoT Hub"; } catch (DeviceAlreadyExistsException) { log.LogWarning($"Device {deviceEvent.LeafDeviceId} already exists, updating only state to 'enabled' and keys"); leafDevice = await registryManager.GetDeviceAsync(deviceEvent.LeafDeviceId); leafDevice.Authentication = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = deviceSymmetricKey, SecondaryKey = deviceSecondaryKey } }; leafDevice.Scope = parentDevice.Scope; leafDevice.Status = DeviceStatus.Enabled; await registryManager.UpdateDeviceAsync(leafDevice); callbackResult.ResultCode = 200; callbackResult.ResultDescriptionn = "Device already existed, we updated the IoT Hub registration to 'enabled'"; } catch (System.Exception exception) { log.LogError($"Exception when adding leaf device: {exception.Message}"); } } } else { log.LogWarning($"Device '{deviceEvent.LeafDeviceId}' is not a valid device, not creating/activating"); callbackResult.ResultCode = 400; callbackResult.ResultDescriptionn = "Device not whitelisted"; } break; case LeafEvent.Operations.delete: try { await registryManager.RemoveDeviceAsync(deviceEvent.LeafDeviceId); callbackResult.ResultCode = 200; callbackResult.ResultDescriptionn = "Device successfully deleted in IoT Hub"; log.LogInformation($"Device deleted '{deviceEvent.LeafDeviceId}'"); } catch (DeviceNotFoundException dle) { callbackResult.ResultCode = 500; callbackResult.ResultDescriptionn = "DeviceNotFoundException occurred when trying to delete the device"; log.LogError($"DeviceNotFoundException when trying to delete leaf device: {dle.Message}"); } catch (System.Exception exception) { callbackResult.ResultCode = 500; callbackResult.ResultDescriptionn = $"Exception when trying to delete the device: {exception.Message}"; log.LogError($"Exception when trying to delete leaf device: {exception.Message}"); } break; case LeafEvent.Operations.disable: try { var device = await registryManager.GetDeviceAsync(deviceEvent.LeafDeviceId); device.Status = DeviceStatus.Disabled; await registryManager.UpdateDeviceAsync(device); callbackResult.ResultCode = 200; callbackResult.ResultDescriptionn = "Device successfully disabled in IoT Hub"; log.LogInformation($"Device disabled: '{deviceEvent.LeafDeviceId}'"); }catch (System.Exception exc) { callbackResult.ResultCode = 500; callbackResult.ResultDescriptionn = $"Error when trying to disable device: {exc.Message}"; } break; } //DM with result to Module (also if error, then Edge module can log locally) serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); var methodInvocation = new CloudToDeviceMethod("ItmCallback") { ResponseTimeout = TimeSpan.FromSeconds(30) }; methodInvocation.SetPayloadJson(JsonConvert.SerializeObject(callbackResult)); try { var response = await serviceClient.InvokeDeviceMethodAsync(deviceEvent.EdgeDeviceId, deviceEvent.EdgeModuleId, methodInvocation); log.LogInformation($"Response status: {response.Status}, payload: {response.GetPayloadAsJson()}"); } catch { //TODO retry? log.LogWarning($"Error in calling DM 'ItmCallback' to module '{deviceEvent.EdgeModuleId}'"); } log.LogInformation("Finished processing LeafDeviceCloudEventGrid function"); }
public void testJsonExploreNestedObjects() { LeafEvent[] argsjsonexp; argsjsonexp = new LeafEvent[] { new LeafEvent("a", "2", false), new LeafEvent("d", "5", false) }; testJsonExplorationParameterised("{a:2, b:{ c: { d:5} } }", 3, 3, 2, argsjsonexp); }
public void testBasicJsonPropertyExplore() { LeafEvent[] argsjsonexp; argsjsonexp = new LeafEvent[] { new LeafEvent("a", "2", false), new LeafEvent("b", "3", false) }; testJsonExplorationParameterised("{a:2, b:3}", 1, 1, 2, argsjsonexp); }
public void testJsonExplorationParameterised(string json, int expectedStartCount, int expectedEndCount, int expectedLeafCount, LeafEvent[] expectedLeafEvents = null) { Console.WriteLine(String.Format("json: {0}", json)); JSONExplorerImpl jsonExplorerImpl = new JSONExplorerImpl(); ExplorationTestListener etl = new ExplorationTestListener(); jsonExplorerImpl.explore(json, etl); Assert.AreEqual(expectedStartCount, etl.startCount, String.Format("expected {0} object start", expectedStartCount)); Assert.AreEqual(expectedEndCount, etl.endCount, String.Format("expected {0} object end", expectedEndCount)); Assert.AreEqual(expectedLeafCount, etl.leafCount, String.Format("expected {0} leaves", expectedLeafCount)); if (expectedLeafEvents!=null) { for ( int done=0; done<expectedLeafEvents.Length; done++) { Assert.AreEqual(expectedLeafEvents[done].propertyName, etl.actualLeafEvents[done].propertyName, String.Format("leaf name {0}", done)); Assert.AreEqual(expectedLeafEvents[done].value, etl.actualLeafEvents[done].value, String.Format("leaf value {0}", done)); Assert.AreEqual(expectedLeafEvents[done].isQuoted, etl.actualLeafEvents[done].isQuoted, String.Format("leaf isQuoted {0} ", done)); } } }
public void testSingleQuoteJsonValue() { LeafEvent[] argsjsonexp; argsjsonexp = new LeafEvent[] { new LeafEvent("a", "2 3", true) }; testJsonExplorationParameterised("{ a:'2 3' }", 1, 1, 1, argsjsonexp); }
public void testEscapedDoubleQuoteJsonValue() { LeafEvent[] argsjsonexp; argsjsonexp = new LeafEvent[] { new LeafEvent("a", "\"1 \"2", true) }; testJsonExplorationParameterised("{ a:\"\\\"1 \\\"2\" }", 1, 1, 1, argsjsonexp); }