Logic Apps - krzysiek861/AvanadeWorkshop Wiki

Checkout branch

If you wish to start from this step, you can checkout the following branch: git checkout feature/logic-apps

Configure Sendgrid.

Go to the Sendgrid resource and click "Configure Account now".

Configure account

In case you see an error that says you need administrator approval, then open a new window in Accenture contex, copy the link and login. You should finally see Sendgrid's landing page.

Landing page

Create a single sender, you should receive a verification e-mail. Once you get it, click the "Verify Single Sender" button.

Email

Now obtain an API Key, go to API Keys and click "Create API Key".

API Key

Put any name of the key, you can select "Full Access", and click "Create & View". You should see the key now, please make sure you have copied it, there will be no chance to see it again!

Let's save the key in the Key Vault. The Key Vault resource is located in your Resource Group. When you open it, find "Secrets".

Create a new secret and call it: "sendgridApiKey". We use this name in the app, so we want to name exactly: "sendgridApiKey". Save it and check if the list of secrets is just like in the picture below.

Last step in the part is to create a Sendgrid template. Under Email API -> Dynamic Template section select "Create a Dynamic Template" and provide the template name.

Then select "Add version". From the design selection choose Blank Template and as a editor we pick Code Editor.

Replace default HTML code with the following:

<html>
<head>
  <title>Player Card: {{fullName}}</title>
  <style>
	body {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.card {
	  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
	  transition: 0.3s;
	  width: 250px;
	  
	}
	.card:hover {
	  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
	}
	.container {
	  padding: 2px 16px;
	}
	img {
		object-fit: fill;
		background: blue;
		width: 250px;
		height: 200px
	}
  </style>
</head>
<body>
	<div class="card">
		<img src="{{{ imageUrl }}}" alt="Avatar">
		<div class="container">
			<h4><b>{{ fullName }}</b></h4>
			<p>Position: {{position}}</p>
			<p>Number: {{number}}</p>
		</div>
	</div>
</body>
</html>

In order to preview your template you can also add the following json to the Test Data tab:

{
	"fullName": "John Doe",
	"imageUrl": "https://th.bing.com/th/id/R.3f28b642568815dd3ddd79ad2238be92?rik=v6pQnCJSQ0%2fXUA&pid=ImgRaw&r=0",
	"position": "MF",
	"number": 10
}

Remember to save your changes! You've probably noticed the template id displayed under your template details. Save that to use in the next step.

Consume message and send an email

Add this code to Avanade.AzureWorkshop.Topics project, Functions.cs

    private const string NewsletterTriggerName = "Newsletter";

    public async Task ProcessNewsletter([ServiceBusTrigger(NewsletterTriggerName, SubscriptionName, Connection = "AzureWebJobsServiceBus")] ServiceBusReceivedMessage message, TextWriter textWriter)
    {
        await ProcessMessage(textWriter, new BaseMessageModel(), async (scope, model) =>
        {
            var newsletterService = scope.Resolve<NewsletterService>();
            await newsletterService.SendNewsletter();
        });
    }

Open SendgridService from Services directory. Put your email (from and to) and the template id (mentioned in the previous step).

public class SendgridService
{
    private readonly PlayersService _playersService;

    public SendgridService(PlayersService playersService)
    {
        _playersService = playersService;
    }

    public async Task<HttpStatusCode> SendEmail()
    {
        var apiKey = GlobalSecrets.SendgridApiKey;
        var client = new SendGridClient(apiKey);
        var from = new EmailAddress("[email protected]", "From Name");
        var to = new EmailAddress("[email protected]", "To Name");
        var templateId = "";

        var playerDetails = _playersService.GetRandomPlayerDetails();
        var msg = MailHelper.CreateSingleTemplateEmail(from, to, templateId,
            new
            {
                fullName = playerDetails.FullName,
                imageUrl = playerDetails.Images.FirstOrDefault(),
                position = playerDetails.Position,
                number = playerDetails.Number
            });
        msg.Subject = $"Player Card: {playerDetails.FullName}";

        var response = await client.SendEmailAsync(msg);

        return response.StatusCode;
    }
}

Create the NewsletterService in the BusinessLogic directory.

public class NewsletterService
{
    private readonly SendgridService _sendgridService;

    public NewsletterService(SendgridService sendgridService)
    {
        _sendgridService = sendgridService;
    }

    public async Task SendNewsletter()
    {
        await _sendgridService.SendEmail();
    }
}

Register the new service in Autofac for both, WepApp and Topics. Look for Global.asax.cs and IocConfig.cs files.

    builder.RegisterType<NewsletterService>();

Redeploy the app.

Create Azure Logic App

Go to Portal Azure and add a new resource.

Select the type Logic App.

Fill in the unique name, select the right region and the plan.

Click "Review and Create" and then "Create". When the resource is created, you can click "Go to resource".

We will use visual designer to add steps to the workflow. Click "Recurrence".

The workflow will be run every 2 minutes (you can set any other interval).

Add another step which sends a message to the Service Bus.

Set the correct topic name and add Content parameter and set some value there.

Save changes. Test connection by running the trigger manually or wait for it. Open Web Jobs logs to check if the message has arrived.

Run history

You can always check web job logs. Open web app and find WebJobs. Click Logs.

⚠️ **GitHub.com Fallback** ⚠️