AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск Все разделы прочитаны

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 04.07.2019, 18:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,459 / 846 (79) +++++++
Регистрация: 28.10.2006
sertandev: How to receive D365FO push notifications using Azure Notification Hubs
Источник: http://devblog.sertanyaman.com/2019/...fication-hubs/
==============

Azure Notification Hubs is a scalable push notification engine of Azure Cloud Platform for sending native notifications to iOS, Android, Windows, Google Chrome, Kindle and many other supported devices and notification services. In this article I will explain how it can be integrated with Dynamics 365 for Finance and Operations, setting up a sample application in Android for receiving native push notifications directly from D365FO, without using any third party applications like the Flow application.


Project demoThis is a rather detailed project and I will do my best to keep it short and simple. It will be something like a combination of my previous blog posts on D365 Native Android connection and Business Events, so it would be a good idea check these posts first from the links below :
How to integrate D365FO with Microsoft Flow using the new Business Events
How to connect a Native Android Application to Dynamics 365 FO
Also we will again be using this blog’s good old D365FO visit schedule example project to test notifications from. So, as a prerequisite to this article, you need to install and deploy this project as described in my previous Business Events blog post..

The steps we are going to take are :
  1. Create a new Firebase cloud messaging project
  2. Create a new Azure notification hub and connect it to the firebase project
  3. Download the demo Android app project and configure it for both firebase and notification hub
  4. Create a new http triggered Azure function to connect to the notification hub
  5. Configure D365 business events and create a new business event in D365FO for visit schedule example
  6. Activate the new business event to call the Azure function you created
Setting up Firebase and Notification Hub

Goto ” https://console.firebase.google.com/ ” and create a new Firebase project. Click on the cloud messaging and click “Add app” or “Register app” or any other button to add an application to project. For package name enter the name of the example android project : “com.sertanyaman.dynamics365test”, leave the rest as it is and follow the wizard steps. Save the JSON file for the configuration of the app later. I have already added the Firebase SDKs in the Android app project, so skip that part (optionally, library upgrade would be good..). Skip the “run your app to verify” step if it still exists in the time you read this article.

Now go to project settings > cloud messaging and copy the “Server key” here to use it later on notification hubs :

Go to the azure portal, and notification hubs page, and add a new notification hub. Go to settings and select Google, and enter the server key you copied here in API key field :

Goto access policies page and copy the value of the “DefaultListenSharedAccessSignature” connection string, later to be used in app setup.

Setting up the Android app

Download the latest version of android example from my github link below and open it in Android Studio :

https://github.com/sertanyaman/nativ...dynamics-365fo

Copy the “google-services.json” file you downloaded before in the root folder of the project. Before you go on with this example, you can optionally enable the google maps and ADAL connection as described in my previous blog for this android app. Then your app will be fully functional.

Run the app and enter the settings, make sure you enter the worker id first you want to receive messages for. The notifications you receive from D365FO will be filtered for this worker, using notification hub’s “tags” property.

Enter the new settings for notification hubs here with the settings you have noted before. Hub name will be the notification hub name, and the listener string is the value you have copied in Notification hub’s access policies :

After this, your application should be successfully connected to the notification hubs. You can send a test message using the Test Send function of notification hubs :

Creating the Azure function to connect D365FO with Notification hubs

In the time of writing, there is no possibility of calling notification hubs directly from a Flow or Logic app. Instead, we will create an Azure function to setup the link between D365FO Business Events and notification hubs. Create a new Azure function project in Visual Studio for “HTTP trigger” as trigger option. Go to nuget packages and add “Microsoft.Azure.NotificationHubs” package; this is the API we will be using to call notification hubs. Once done, we will use the following code to create a push message for notification hubs, and call the hub to send it :

......................using Newtonsoft.Json;using Microsoft.Azure.NotificationHubs;using Microsoft.Azure.NotificationHubs.Messaging;namespace NHubsTestFunction{ public static class NHubsVisitSend { [FunctionName("NHubsVisitSend")] public static async Task Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { string hubName = ""; string endPointConn = @"Endpoint="; log.LogInformation("C# HTTP trigger function processed a request."); // Define the notification hub. NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(endPointConn, hubName); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); string worker = data["worker"] ?? ""; string custName = data["custname"] ?? ""; string custAddress = data["address"] ?? ""; var message = String.Format("A new visit is scheduled for you : {0}\n{1}", custName, custAddress); // Define an Android alert. var androidAlert = "{\"data\":{\"message\": \"" + message + "\"}}"; hub.SendFcmNativeNotificationAsync(androidAlert, worker).Wait(); return new OkObjectResult("Done"); } }}In here, you need to define the two string variables, ‘hubName’ and ‘endPointConn’ for configuration. End point conn is the connection string in your notification hub’s access policies tab for “full” access. Realize that we will be giving worker id you receive as “tag” parameter for the notification sending function. This way, each device will only receive the data associated with the worker they are registered to.

Build and publish the function to your Azure subscription. Once finished, do another test for this step to see everything works smooth. Go to the page of the Azure function you published from Azure portal and run a test using a test payload like shown below :

You should be receiving the test notification in the app you installed.

Configuring D365FO Business Events to connect Azure Function

And eventually the last step, we will configure D365FO side to connect the rest. To start, you need to enable the business events, then download and setup the visit schedule example project and deploy its business events, as described in my previous blog post D365FO integration with business events. Build the visit schedule project and setup the business event as described in the blog post; but do not create a Flow for it, instead we will be using the Azure function we have just created.

To link this business event to the azure function, we will use a special endpoint which will be calling the Azure function’s HTTP trigger. In the time of writing, D365FO HTTPS type of endpoints require the target url value to be coming from an Azure key vault secret.. So we must first create a key vault and a key vault secret. First you need to create a new app registration in AAD for this vault secret access. Create one and from the app permissions, give access permission to the Key Vault:

Go to the certificates&secrets and create a new client secret. Note both the app registration ID and the client secret for the Endpoint setup. Close this window and go to Azure key vaults. Create a new key vault if you do not have one already :


Now go to access policies of key vault and click add new. Select the configuration template as shown below and for “Select principal”, search the name of the app registration you have just created:

Save this one and keep the vault window open, open a new portal window go to the page of your azure function (the page you tested the function before). Click “Get function URL” button in the menu and copy the URL of the function :

On the vault window, go to secrets and add a new one. Give any name you like (I give it “BusiEvents” for example) and note it for future, paste the Azure function url as the value of the key.

Now go back to D365FO and open the Business Events setup page. If you did not refresh the catalog yet, do it from the manage menu.

Then go to the Endpoints tab and create a new HTTPS type of endpoint. Fill in the values here :

  • End point name : Just give a unique name for your endpoint
  • Application ID : The application registration ID you created for Key Vault access
  • Azure application secret : the client secret you have created in application registration
  • Key vault DNS name : full DNS name of the key vault, just copy it from the key vault dashboard page from Azure portal
  • Key vault secret name : name of the secret you have created with the Azure function URL as value.
Click OK and if everything is validated, your new endpoint should be saved successfully. Afterwards go to the Business Events catalog (list) select the “AndVisitScheduleAddedBusinessEvent” entry and click Activate. From here select the new endpoint you have just created.

Save and you are done..

Testing

To test, enter some new records for your chosen worker (the one you entered in the parameters of your Android app) in the visit schedules form:

You may need to wait for a while, like up to 5 minutes for the push notification to come. Here in my test it has came successfully after 2 minutes :

Troubleshooting

If you do not receive any message, first place to look at should be the Business Event batch running or not (in preview version..). If not, start it from the Business Events menu. Second place is the Errors tab in the Business Event setup form. If there is a problem with authorization of the endpoint, it should be displayed here. If you have authorization errors, just create a new client secret for your azure app registration and create another endpoint. Then activate your event to that one instead. The business events feature is still in preview and does not always work OK, so you might need to try a couple times to get it working (like I did )





Источник: http://devblog.sertanyaman.com/2019/...fication-hubs/
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
sertandev: How to integrate D365FO with Microsoft Flow using the new Business Events Blog bot DAX Blogs 0 23.05.2019 16:11
sertandev: Empowering D365 FO service endpoints with Azure API Management service Blog bot DAX Blogs 0 15.05.2019 22:11
Navigate Into Success: How do I: Really set up Azure Active Directory based authentication for Business Central APIs Blog bot NAV: Blogs 0 17.02.2019 04:43
sertandev: How to connect a Native Android Application to Dynamics 365 FO Blog bot DAX Blogs 0 18.10.2018 18:11
axsa: How to transform an automated business process into an intelligent business process using Dynamics and Azure ML Blog bot DAX Blogs 1 29.10.2014 15:10
Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 01:57.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.