Search code examples
c#azureazure-functionsazure-storage-queues

Fail to bind azure queue storage with azure functions(scheduler trigger) in portal


I am building a Azure function app to access the Azure Queue Storage(Scheduler Trigger), retrieve messages, and send emails using SendGrid.

I've spent a lot of time debugging and crawling StackOverFlow but still received the same error message.

Here is the error message.

[Error] Exception while executing function: Functions.ScheduledMailCSharpHobby. mscorlib: Exception has been thrown by the target of an invocation. Microsoft.WindowsAzure.Storage: Settings must be of the form "name=value".

FILE: run.csx

#r "SendGrid"
#r "Microsoft.WindowsAzure.Storage"

using System;
using SendGrid.Helpers.Mail;
using Microsoft.Azure;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;


public static Mail Run(TimerInfo myTimer, TraceWriter log)
{
    var today = DateTime.Today.ToShortDateString();
    log.Info($"Generating daily report for {today} at {DateTime.Now}");
    
    Mail message = new Mail()
    {
        Subject = $"Daily Report for {today}"
    };

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("serverlessbdbxxxxxxx");
    // Get queue... create if does not exist.
    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
    CloudQueue queue = queueClient.GetQueueReference("memberqueue");
    // Peek at the next message
    CloudQueueMessage peekedMessage = queue.PeekMessage();

    // Display message.
    log.Info(peekedMessage.AsString);

    var mail_content = peekedMessage.AsString;

    Content content = new Content
    {
        Type = "text/plain",
        Value = $"Hi! {mail_content}"
    };

    message.AddContent(content);
    return message;
}

FILE: function.json

{
  "bindings": [
    {
      "type": "timerTrigger",
      "name": "myTimer",
      "schedule": "0 0 17 * * *",
      "direction": "in"
    },
    {
      "type": "sendGrid",
      "name": "$return",
      "direction": "out",
      "apiKey": "AzureWebJobsSendGridApiKey",
      "from": "Azure Functions <samples@functions.com>",
      "to": "xxxx@gmail.com"
    }
  ]
}


Solution

  • Problem is caused by this line.

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("serverlessbdbxxxxxxx");
    

    To access the Storage account connection string, you need to

    1. Store the connection string in Application settings of Function app on portal.

      enter image description here

      enter image description here

    2. Get the connection string with GetEnvironmentVariable().

      CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("StorageConnectionString"));