Search code examples
azureazure-functionsazureservicebusazure-eventhub

Error indexing method 'IntegrationFunction' Can't convert from type 'Microsoft.Azure.EventHubs.EventData


I'm struggling to understand why I'm receiving the following error with my Azure function.

Error:

Error indexing method 'IntegrationFunction' Can't convert from type 'Microsoft.Azure.EventHubs.EventData

The function is reading data from an Azure Service Bus and transforming it before posting it to an Azure Event Hub and another Azure Service Bus.

Function:

[FunctionName("IntegrationFunction")]
[return: ServiceBus("%Transactions:SB:Transactions:ProcessorUpdateQueue%", Connection = "Transactions:SB:Transactions")]
public async Task<ServiceBusMessage> Run(
    [ServiceBusTrigger(
        "%Transactions:SB:Transactions:ReceiveTopic%",
        "%Transactions:SB:Transactions:AnalyticsTopicSubscription%",
        Connection = "Transactions:SB:Transactions")]
    string inputMsg,
    [EventHub("%Transactions:EVH:Transactions:Hub%", Connection = "Transactions:EVH:Transactions")] IAsyncCollector<EventData> outputEvent,
    ILogger log)
{
    if (string.IsNullOrWhiteSpace(inputMsg))
    {
        throw new ArgumentNullException(nameof(inputMsg));
    }

    log.LogInformation($"Service bus topic trigger function processing message: {inputMsg}");
    
    var retailTransaction = JsonConvert.DeserializeObject<RetailTransaction>(
        inputMsg,
        JsonSerialisationUtils.SerialiserSettings);
    
    if (retailTransaction == null)
    {
        throw new JsonException("Deserialized transaction was null");
    }

    try
    {
        // Transform
        var transaction = retailTransaction.ToDto();
        
        // Post to event hub
        await outputEvent.AddAsync(new EventData(ToByteArray(transaction)));

        log.LogInformation($"Transaction {transaction.TransactionNumber} processed.");

        // Post to service bus
        return retailTransaction.ToUpdateServiceBusMessage(processorId);
    }
    catch (Exception e)
    {
        log.LogError(e, "Error mapping transaction.");
    }

    return null;
}

Solution

  • You need to use Azure.Messaging.EventHubs for extension version 5.x+. Thanks @Jesse Squire for the comment.

    You can also refer to the MS Doc which says the same.

    enter image description here

    • I have the below code with given .csproj file in place and it works as expected.
    using System;
    using System.Text;
    using System.Threading.Tasks;
    using Azure.Messaging.EventHubs;
    using Azure.Messaging.ServiceBus;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    
    namespace _78237298
    {
        public class IntegrationFunction
        {
            [FunctionName("IntegrationFunction")]
            [return: ServiceBus("%OtherServiceBus:QueueName%", Connection = "OtherServiceBus:ConnectionString")]
            public async Task<ServiceBusMessage> Run(
                [ServiceBusTrigger(
                "%Transactions:SB:Transactions:ReceiveTopic%", 
                "%Transactions:SB:Transactions:AnalyticsTopicSubscription%", 
                Connection = "Transactions:SB:Transactions")]
                string inputMsg,
                [EventHub("%Transactions:EVH:Transactions:Hub%", Connection = "Transactions:EVH:Transactions")] IAsyncCollector<EventData> outputEvent,
                ILogger log)
            {
                if (string.IsNullOrWhiteSpace(inputMsg))
                {
                    throw new ArgumentNullException(nameof(inputMsg));
                }
    
                log.LogInformation($"Service bus topic trigger function processing message: {inputMsg}");
    
                var retailTransaction = JsonConvert.DeserializeObject<RetailTransaction>(
                    inputMsg);
    
                if (retailTransaction == null)
                {
                    throw new JsonException("Deserialized transaction was null");
                }
    
                try
                {
                    var transaction = retailTransaction.ToDto();
                    log.LogInformation($"Transaction {transaction.TransactionNumber} processed.");
                    // Post to event hub
                    await outputEvent.AddAsync(new EventData(ToByteArray(transaction)));
    
                    log.LogInformation($"Transaction {transaction.TransactionNumber} processed.");
    
                    // Create ServiceBusMessage instance
                    var serviceBusMessage = new ServiceBusMessage(JsonConvert.SerializeObject(transaction));
                    serviceBusMessage.MessageId = transaction.TransactionNumber.ToString();
                    serviceBusMessage.Subject = "Transaction Updated"; 
    
                    return serviceBusMessage;
                }
                catch (Exception e)
                {
                    log.LogError(e, "Error mapping transaction.");
                }
                return null;
            }
            private static byte[] ToByteArray(object obj)
            {
                var json = JsonConvert.SerializeObject(obj);
                return Encoding.UTF8.GetBytes(json);
            }
        }
    
        public class RetailTransaction
        {
            public string TransactionNumber { get; set; }
            public decimal Amount { get; set; }
    
            public Transaction ToDto()
            {
                return new Transaction
                {
                    TransactionNumber = this.TransactionNumber,
                    Amount = this.Amount
                };
            }
        }
        public class Transaction
        {
            public string TransactionNumber { get; set; }
            public decimal Amount { get; set; }
        }
    }
    

    .csproj-

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <AzureFunctionsVersion>v4</AzureFunctionsVersion>
        <RootNamespace>_78237298</RootNamespace>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Azure.Messaging.EventHubs" Version="5.11.1" />
        <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.EventHubs" Version="6.2.0" />
        <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="5.14.0" />
        <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.3.0" />
      </ItemGroup>
      <ItemGroup>
        <None Update="host.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Update="local.settings.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
          <CopyToPublishDirectory>Never</CopyToPublishDirectory>
        </None>
      </ItemGroup>
    </Project>
    

    Output-

    Event Hub-

    enter image description here

    2nd Service Bus-

    enter image description here