private async Task InvokeMethod( string methodName, PurchaseTicketPayload purchaseTicketPayload) { TimeSpan responseTimeoutInSeconds = TimeSpan.FromSeconds(30); var methodInvocation = new CloudToDeviceMethod(methodName) { ResponseTimeout = responseTimeoutInSeconds }; var payload = JsonConvert.SerializeObject(purchaseTicketPayload); methodInvocation.SetPayloadJson(payload); try { // Invoke the direct method asynchronously and get the response from the simulated device. var response = await serviceClient.InvokeDeviceMethodAsync(purchaseTicketPayload.DeviceId, methodInvocation); if (response != null) { Console.WriteLine("Response status: {0}, payload:", response.Status); Console.WriteLine(response.GetPayloadAsJson()); } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }
public async Task <IActionResult> Run(string deviceId, string direction) { // create command message CloudToDeviceMethod methodInvocation = new CloudToDeviceMethod("ReceiveCommandGateChange") { ResponseTimeout = TimeSpan.FromSeconds(30) }; try { cmdGateDirectionUpdate command = new cmdGateDirectionUpdate() { Direction = (GateDirection)Enum.Parse(typeof(GateDirection), direction) }; methodInvocation.SetPayloadJson(JsonConvert.SerializeObject(command)); } catch (System.ArgumentException) { return(new BadRequestObjectResult("value of 'direction' must be 'In' or 'Out'")); } try { // Invoke the direct method and get the response from the simulated device. var response = await serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation); Console.WriteLine("Response status: {0}, payload:", response.Status); Console.WriteLine(response.GetPayloadAsJson()); } catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException ex) { return(new BadRequestObjectResult($"Device '{deviceId}' either does not exist or is not responding: {ex.Message}")); } return(new OkObjectResult($"Device {deviceId} updated to new direction: {direction}")); }