Alex Gordon
Alex Gordon

Reputation: 60731

binding to a blob in blobtriggered function

How do we bind to properties inside of a blob?

My bindings:

    public static async Task Run(
        [BlobTrigger("%triggerContainer%/{name}")] Stream myBlob,
        [Blob("%triggerContainer%/{name}", Read)]  CloudBlockBlob @in,
        [Blob("%outputContainer%/{name}", Write)] CloudBlockBlob @out,
        string name, ILogger log)
    {

I'd like to be able to change the blobtrigger type to a POCO:

[BlobTrigger("%triggerContainer%/{name}")] MyPoco myBlob

Where MyPoco might be something like this:

public class MyPoco
{
   public string id {get;set;}
   public string filename {get;set;}
}

From within the function I'd like to be able to do something like this:

var thisId = myBlob.id;
var thisfileName = myBlob.filename;

How do we bind to the actual contents of the blob with a POCO object?

According to this:

JavaScript and Java functions load the entire blob into memory, and C# functions do that if you bind to string, Byte[], or POCO.

Upvotes: 0

Views: 268

Answers (1)

suziki
suziki

Reputation: 14088

First write an IExtensionConfigProvider that registers converters as needed,

internal class CustomBlobConverterExtensionConfigProvider : IExtensionConfigProvider
{
    public void Initialize(ExtensionConfigContext context)
    {
        context.AddConverter<Stream, MyPoco>(s =>
        {
            // read and convert
            return new MyPoco();
        });

        context.AddConverter<ApplyConversion<MyPoco, Stream>, object>(p =>
        {
            MyPoco value = p.Value;
            var stream = p.Existing;

            TextWriter writer = new StreamWriter(stream);
            // write the value to the stream
            writer.FlushAsync().GetAwaiter().GetResult();

            return null;
        });
    }
}

Then, you register this config provider with the host builder on startup:

var builder = new HostBuilder()
    .ConfigureWebJobs(b =>
    {
        b.AddAzureStorageCoreServices()
        .AddAzureStorage()
        .AddExtension<CustomBlobConverterExtensionConfigProvider>();
    })

Then bind your BlobTrigger function to Mypoco:

public void BlobTrigger([BlobTrigger("test")] Mypoco item, ILogger logger)
{
    // process item
}

For more information, have a look of this doc.

Upvotes: 1

Related Questions