0

I have an Azure IOT Hub that a few Arduino devices connect to from time to time. I also have an Azure Queue that can contain json strings that I want to send to the individual devices when they are connected.

I followed example for creating a webjob that gets called when data arrives in the queue. I also followed example that schedules a job for sending data to the IOT device when it connects. Both work correctly when run individually.

I combined these examples so when the ProcessQueueMessage() gets called because something arrived in the queue, I would then schedule a job to send that data to the IOT device.

public static async Task ProcessQueueMessage([QueueTrigger("inbox")] string message, ILogger logger)
{
  logger.LogInformation(message);
  Message = message;

  string methodJobId = Guid.NewGuid().ToString();
  await StartMethodJob(methodJobId, Message);
  MonitorJob(methodJobId).Wait();
}

However, doing so caused a SystemNullException and I'm not sure why. All the functions are static and if I step through it I can see that the incoming parameters have values. As a result, it moves the queue item into another queue "inbox-poison".

info: Function.ProcessQueueMessage.User[0]
      {"TransId":3517,"DeviceId":"Huzz_2_2_2","PriceAlert":{"Price":"High","Variance":0.0,"DisplaySetting":1,"Duration":60}}
fail: Function.ProcessQueueMessage[0]
      Executed 'Functions.ProcessQueueMessage' (Failed, Id=556812ab-4a58-4ae1-9f4f-6336962d92d2)
Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.ProcessQueueMessage ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at IncomeEligible.Alerts.Functions.StartMethodJob(String jobId, String json) in C:\source\repos\Income_Eligible_Price_Display\src\IncomeEligible.Alerts\IncomeEligible.Alerts\Functions.cs:line 46
   at IncomeEligible.Alerts.Functions.ProcessQueueMessage(String message, ILogger logger) in C:\source\repos\Income_Eligible_Price_Display\src\IncomeEligible.Alerts\IncomeEligible.Alerts\Functions.cs:line 80
   at Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker`2.InvokeAsync(TReflected instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\VoidTaskMethodInvoker.cs:line 20
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync(Object instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker, ParameterHelper parameterHelper, CancellationTokenSource timeoutTokenSource, CancellationTokenSource functionCancellationTokenSource, Boolean throwOnTimeout, TimeSpan timerInterval, IFunctionInstance instance) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 584
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 531
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, IFunctionOutputDefinition outputDefinition, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 467
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 277
   --- End of inner exception stack trace ---
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 321
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsyncCore(IFunctionInstanceEx functionInstance, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 117

The following is my program:

using Microsoft.Azure.Devices;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace IncomeEligible.Alerts
{
  public class Functions
  {
    private static JobClient jobClient;
    private static int Count = 0;
    private static string Message = "";

    private static string deviceId = "Huzzah_w_DHT22";

    private const string DeviceConnectionString =
      "HostName=...";

    private const string HubConnectionString =
      "HostName=...";

    public static async Task MonitorJob(string jobId)
    {
      JobResponse result;
      do
      {
        result = await jobClient.GetJobAsync(jobId);
        Console.WriteLine("Job Status : " + result.Status.ToString());
        Thread.Sleep(2000);
      } while ((result.Status != JobStatus.Completed) &&
               (result.Status != JobStatus.Failed));
    }

    public static async Task StartMethodJob(string jobId, string json)
    {
      CloudToDeviceMethod directMethod =
        new CloudToDeviceMethod("SetPriceAlert", TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));

      directMethod.SetPayloadJson(json);

      JobResponse result = await jobClient.ScheduleDeviceMethodAsync(jobId,
        $"DeviceId IN ['{deviceId}']",
        directMethod,
        DateTime.UtcNow,
        (long)TimeSpan.FromMinutes(2).TotalSeconds);

      Console.WriteLine("Started Method Job");
    }

    public static async Task ProcessQueueMessage([QueueTrigger("inbox")] string message, ILogger logger)
    {
      logger.LogInformation(message);
      Message = message;

      string methodJobId = Guid.NewGuid().ToString();
      await StartMethodJob(methodJobId, Message);
      MonitorJob(methodJobId).Wait();

    }

  }
}

If working correctly, does this approach make sense or is it better or setup an Event Hub trigger or IOT Hub trigger that detects when a device is connected and calls a function to have it send the json to the connected device?

Thank you for your help!

PKonstant
  • 834
  • 2
  • 15
  • 32

1 Answers1

0

jobClient isn't assigned any value.

Also you don't want to mix async with blocking calls like .Wait() and Thread.Sleep(). Use await and await Task.Delay() instead.

  • you were right! jobClient wasn't being assigned. It took me a week to realize that even though you pointed it out to me. Per your comment, I looked at the code, I didn't think I was really using but today I saw that I was using it in the StartMethodJob() and fixed the issue and the problem was resolved so thank you again. – PKonstant Jul 11 '19 at 20:25