Monday, April 3, 2017

Using Azure from .NET Console App for Exception Notifications

Microsoft Azure helps out again...

I recently worked on a project where a .NET console app needed to run consistently throughout a weekend, without interruption. If the app threw an exception from which it could not recover, I wanted to be notified right away so I could login and resolve the issue.

The server where I was asked to run the application did not have the ability to send email, so the solution I came up with was to send a message from the app to an Azure Service Bus queue and then use an Azure Logic App to read from the queue and send an email to my account.

Below is a C# method that will send a message to an Azure Service Bus queue:

public static void PostExceptionToAzureSBQueue(Exception ex)
{
  try
  {
    var connectionString = Settings1.Default.ExceptionServiceBusQueueConnectionString;
    var queueName = Settings1.Default.ExceptionServiceBusQueueName;

    var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
    string msgText = "Data migration exception occurred.\n\n";
    var message = new BrokeredMessage(new MemoryStream(Encoding.UTF8.GetBytes(msgText + ex.ToString())), true);
    client.Send(message);
  }
  catch (Exception ex2)
  {
    log.WarnFormat("Error occurred attempting to send Azure Service Bus Queue message: Exception={0}", ex2.Message);
  }
}
The Azure Logic app only needs two steps: 1) Get queue message and 2) Send email via Office 365 Outlook. In the second step, simply place the "Content" data from the queue message into the Body field for the email to send. You can set the email priority to High and deliver the email to multiple recipients if desired.

This is another example of where Azure can help with general .NET development... even "old school" .NET console apps.

No comments:

Post a Comment