0

I'm new to Azure development, and have below function

        [FunctionName("BindingTrigger")]
        public async Task<IActionResult> BindingTrigger(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log,
            [Blob("sample-blob/test.txt", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream outputBlob,
            [CosmosDB("azurefunctions", "FileContents", Connection = "CosmosConnStr", CreateIfNotExists = true)] IAsyncCollector<FileContents> documents)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                await documents.AddAsync(new FileContents
                {
                    PartitionKey = Guid.NewGuid().ToString(),
                    RowKey = "1",
                    Name = "test.txt",
                    Contents = outputBlob.Length.ToString()
                });
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
            }


            return new OkObjectResult($"Size of file: {outputBlob.Length}");
        }

When i execute it logs "C# HTTP trigger function processed a request.", but nothing happens after. No exception, and function timesout after 30mins.

I was trying with CosmosDB Emulator running in docker. Tried it with Azure CosmosDB instance, with same result. Also thinking if it could be issue with my system, i tried with another system, and same result. Any idea what could be wrong?

1
  • Do you have the setting CosmosConnStr populated with a connection string or are you using MSI auth? Are you debugging locally? Do you see any error logs or Events when debugging locally? Commented Nov 14, 2023 at 18:17

1 Answer 1

0

Make sure you are setting correct Data in File content according to your Azure CosmosDB schema and using a valid Connection String for your AzureWebJobsStorage and CosmosConnStr as per the comment by Matias Quaranta.

I have created my CosmosDB Database and Container by referring this MS Document.

My Function code:-

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

public class FileContents
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("category")]
    public string Category { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("isComplete")]
    public bool IsComplete { get; set; }
}

public static class MyFunctions
{
    [FunctionName("BindingTrigger")]
    public static async Task<IActionResult> BindingTrigger(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log,
        [Blob("sample-blob/test.txt", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream outputBlob,
        [CosmosDB(
            databaseName: "ToDoList",
            containerName: "Items", // Replace with your container name
            Connection = "CosmosConnStr",
            CreateIfNotExists = true)] IAsyncCollector<FileContents> documents)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        try
        {
            if (outputBlob != null)
            {
                outputBlob.Position = 0; // Reset stream position

                // Deserialize the JSON document structure based on your Cosmos DB schema
                // Modify this according to the actual data you want to insert
                var fileContent = new FileContents
                {
                    Id = "1",
                    Category = "personal",
                    Name = "groceries",
                    Description = "Pick up apples and strawberries.",
                    IsComplete = false
                };

                await documents.AddAsync(fileContent);

                return new OkObjectResult("Data inserted into Cosmos DB");
            }
            else
            {
                log.LogError("Blob is null or inaccessible.");
                return new BadRequestObjectResult("Blob is null or inaccessible.");
            }
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Error processing the request");
            return new StatusCodeResult(StatusCodes.Status500InternalServerError);
        }
    }
}

My local.settings.json:-

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=siliconstrg89;AccountKey=xxxxxxxxxx+AStEQBMoA==;EndpointSuffix=core.windows.net",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "CosmosConnStr": "AccountEndpoint=https://silicon-cosmos.documents.azure.com:443/;AccountKey=xxxxxxxxxxAoACDb4rmfgA==;"
  }
}

Output:-

enter image description here

enter image description here

Your code according to your schema should look like below:-

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading.Tasks;

public class FileContents
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public string Name { get; set; }
    public string Contents { get; set; }
}

public static class MyFunctions
{
    [FunctionName("BindingTrigger")]
    public static async Task<IActionResult> BindingTrigger(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log,
        [Blob("sample-blob/test.txt", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream outputBlob,
        [CosmosDB("azurefunctions", "FileContents", Connection = "CosmosConnStr", CreateIfNotExists = true)] IAsyncCollector<FileContents> documents)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        try
        {
            if (outputBlob != null)
            {
                outputBlob.Position = 0; // Reset stream position
                await documents.AddAsync(new FileContents
                {
                    PartitionKey = Guid.NewGuid().ToString(),
                    RowKey = "1",
                    Name = "test.txt",
                    Contents = outputBlob.Length.ToString()
                });

                return new OkObjectResult($"Size of file: {outputBlob.Length}");
            }
            else
            {
                log.LogError("Blob is null or inaccessible.");
                return new BadRequestObjectResult("Blob is null or inaccessible.");
            }
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Error processing the request");
            return new StatusCodeResult(StatusCodes.Status500InternalServerError);
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

FYI you haven't answered the OP's question. That is... what you posted is your own way of approaching the problem, without identifying/fixing the OP's specific issue. Also: Please do not upload images of code/data/errors. (there are many reasons in that meta post)
Note that there's even a comment under the question, asking for clarification. Until the OP edits their question and adds more details, there's nothing to answer.
Point Noted @DavidMakogon I have given the code in the text format, and the Output image is given to show the success without timeout. I have drafted the solution based on this ask "but nothing happens after. No exception, and function timesout after 30mins" of Op. My Function binding code sets the schema in json and then inserts it with the help of cosmosDb binding which is missing in the Op's Function code. I have also added the custom logging to fetch the success log in the Http Browser request which is missing in Op's code. I hope, this method will help Op fix the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.