# Azure Function : Read messages from queue and update record in dataverse

In the previous article, I described how a message can be sent from D365 to the Azure service bus queue.  
Refer - [send a message to azure service bus queue from Dataverse](https://hashnode.com/post/cll4vjz7z00010ammduhi0itp)

The messages that are in the queue can be processed, we can either use power automate cloud flow or the azure function for the same. Since the prev article was about the power automate flow, let me create an azure function to read the message and post an update back to dataverse to update account's description

### Creating an Azure function

Go to the visual studio and create a new project and look for azure function template

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691732637762/7ce2211e-0ff4-440b-9396-421281166723.png align="center")

Configure the project

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691732706874/57192011-5932-4493-be4f-91e24b1ba1d2.png align="center")

Provide additional information, choose the function, connection string setting name and queue name and create the project

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691732743919/671b48c5-85c5-4f36-8cfa-7ea1e6863566.png align="center")

1. Install Packages  
    The below packages have been added
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691732886461/a8b7bc5b-8bbf-442a-bb13-a176c3e767c1.png align="center")
    
2. Updating the connection string in the local.settings.json
    
    \- For the service bus connection string go to the Azure portal and under the service bus namespace click on the shared access policies and look for RootManageSharedAccessKey and pick the primary connection string  
    \- For the dataverse connection string, we need the service principal user to be created. The setup can be found here
    
    [Register the app in azure active directory](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/walkthrough-register-app-azure-active-directory)  
    [Manage application users in the power platform](https://learn.microsoft.com/en-us/power-platform/admin/manage-application-users)
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691732974762/b50488a3-1d7a-40c5-a415-be84f9777bd1.png align="center")
    
3. Writing the Azure Function  
    \- The project structure looks below
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691733785735/40f01c1e-e018-4550-a4ea-c995eb62cfa5.png align="center")
    
    ```csharp
    [assembly: FunctionsStartup(typeof(FunctionReadQueueMessages.Startup))]
    namespace FunctionReadQueueMessages
    {
    
        public class Startup : FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
                var configuration = builder.GetContext().Configuration;
    
                builder.Services
                    .AddScoped((_)=>
                        new ServiceClient(configuration["dataverseconnectionstring"]));
            }
            public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
            {
                builder.ConfigurationBuilder.AddEnvironmentVariables().Build();
            }
        }
    
        public class UpdateAccountFunction
        {
            private readonly ServiceClient _serviceClient;
            public UpdateAccountFunction(ServiceClient serviceClient)
            {
                _serviceClient = serviceClient;
            }
    
            [FunctionName("UpdateAccountFunction")]
            public void Run([ServiceBusTrigger("account-queue", Connection = "servicebusconnectionstring")] string myQueueItem, ILogger log)
            {
                try
                {
                    log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
                    // Parse the incoming message
                    // For simplicity, assuming the message contains JSON with account ID and updated fields
                    var accountUpdateData = Newtonsoft.Json.JsonConvert.DeserializeObject<AccountUpdateData>(myQueueItem);
                    // Retrieve the account by its ID
                    Entity account = _serviceClient.Retrieve("account", accountUpdateData.Accountid, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
    
                    // Update account fields
                    account["description"] = $"Hello {accountUpdateData.Name} - Message processed in Azure queue successfully";
                    account["accountid"] = accountUpdateData.Accountid;
                    // Update the account record in Dynamics 365
                    _serviceClient.Update(account);
                }
                catch (Exception ex)
                {
                    log.LogError(ex, "An error occurred");
                }
            }
        }
    }
    // Define a class to hold account update data
    public class AccountUpdateData
    {
        public Guid Accountid { get; set; }
        public string Name { get; set; }
    }
    ```
    
    The above code reads messages from the queue and updates the account record in the dataverse with a description
    
    1. Building the Azure function  
        we can run the function locally, test, debug and then publish it to the azure function.
        
    2. Publish the Azure Function
        
        Right-click on the Project and click publish, which will lead to the below screen
        
        ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734075360/835e4331-f104-4d8a-8990-37792708ce60.png align="center")
        
        ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734094292/d6d728ab-28e0-45b9-81d6-d75b85b310ed.png align="center")
        
        Create a new function app or choose the existing one  
        \- Create new
        
        ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734161893/5612f9ab-ddf6-4c81-8054-162597e2104b.png align="center")
        
        * Existing function app
            
            ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734236152/ed9cea33-cca1-4f0c-9e1e-df2890a741a4.png align="center")
            
            I will choose the existing one since I have added it already and then configure the app settings
            
            ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734283465/2d49f3d9-f9ff-4daa-973f-41bbcae057b6.png align="center")
            
            Add both servicebusconnectionstring and dataverseconnectionstring and click ok
            
            ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734341054/f2c41c62-91d8-4b80-91b2-9632e0a72056.png align="center")
            
            Publish
            
            ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734388060/2bfce29d-99a4-479d-b153-5f57addc64ac.png align="center")
            
            1. Viewing the Azure function in the portal  
                go to the Azure portal and search for the function app
                
                ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734506713/f74f5558-4c3d-49dc-9912-fc43238224f6.png align="center")
                
            2. Testing the function
                
                Heading over to Dynamics 365 and adding a new account and save
                
                ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734711986/1b6cc060-79ad-4eec-acae-7c3341586787.png align="center")
                
            3. The account description is now updated
                
                ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734828196/a66fed2b-6051-409f-9544-77b01569e4ce.png align="center")
                
4. Testing locally
    

For this, I will disable the Azure function in the portal

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734907681/4372db61-fc9e-47a4-9acc-2ae297245dbb.png align="center")

Now, send a message to the service bus queue from Dataverse

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691734968143/6b4b9369-4521-4703-9d2f-2d2dbfc500a6.png align="center")

Added a new record, since the azure function is stopped, we can see the message in the service bus queue.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691735033819/8065e697-fa79-488d-860b-25bb749f6bf4.png align="center")

Running the azure function from visual studio

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691735150103/b1556b21-bebf-4cd3-9df0-1ed40bf48edb.png align="center")

Notice, the function has picked up the message from the queue and processed it successfully

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691735259509/9b703bff-aded-4546-82cd-2a72a2af2671.png align="center")

Summary :  
This way azure functions and a service bus can be utilized to send messages from Dataverse and also to process those messages. This helps in offloading long-running code to Azure and keep the plugins lightweight while the azure can do the heavy lifting.

Other useful links  
[Temmy raharjo's blog](https://temmyraharjo.wordpress.com/2022/07/09/how-to-make-azure-functions-dataverse-service-client/)
