azure functions
40 TopicsWhat's the secret sauce for getting Functions API to work with static web site?
I'm brand new, got my first Azure static web site up and running so that's good! Now I need to create some images in code and that's fighting me tooth and nail. The code to generate the image looks like this: using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Extensions.Logging; using SkiaSharp; using System.Diagnostics; using System.IO; using System.Net; namespace Api { public class GenerateImage { private readonly ILogger _logger; public GenerateImage(ILoggerFactory loggerFactory) { Debug.WriteLine($"GenerateImage.GenerateImage()"); _logger = loggerFactory.CreateLogger<GenerateImage>(); } // http://localhost:7071/api/image/124 works [Function("GenerateImage")] public HttpResponseData Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "image/{id}")] HttpRequestData req, string id) { int width = 200, height = 100; Debug.WriteLine($"GenerateImage.Run() [id={id}]"); using var bitmap = new SKBitmap(width, height); using var canvas = new SKCanvas(bitmap); canvas.Clear(SKColors.LightBlue); var paint = new SKPaint { Color = SKColors.Black, TextSize = 24, IsAntialias = true }; canvas.DrawText($"ID: {id}", 10, 50, paint); using var ms = new MemoryStream(); bitmap.Encode(ms, SKEncodedImageFormat.Png, 100); ms.Position = 0; var response = req.CreateResponse(HttpStatusCode.OK); response.Headers.Add("Content-Type", "image/png"); response.Headers.Add("Cache-Control", "public, max-age=86400"); // 1 day // response.Body = ms; ms.CopyTo(response.Body); return response; } } } and if I navigate to http://localhost:7071/api/image/124 (for example) it happily generates an image with the number 124 in it. But if I add the HTML tag <img src="/api/image/123" alt="Generated Image"> to one of my other web pages, it says there's no such page. Apparently this is because my web pages are coming from my web site and it's at https://localhost:7154 and it doesn't know how to contact the Functions API. My staticwebapp.config.json looks like this: { "routes": [ { "route": "/api/*", "allowedRoles": [ "anonymous" ] } ], "navigationFallback": { "rewrite": "/index.html", "exclude": [ "/api/*" ] } } What am I missing?30Views0likes1CommentCan't access http context user claims in Azure Function
Background: Create an Azure Function (.NET Core & C#) that will be consumed in a SPO App. We created an Entra App Registration for the Azure Function and added App Roles for this App Registration where the App Role is using “Users/Group”, but not “Application”. Issue: In the SPO App (deployed in SPO Page), we can see the user claim and App Registration’s - App Role in the context of the user that’s hitting the SPO Page (thru Authorization header), however, in the Azure Function code the req.HttpContext.User.Claims object is empty. So what is required or missing from a configuration perspective either in the Azure Function or App Registration to make this work?118Views0likes1CommentAzure Function App Http Javascript render simple html file to replicate jsrsasign sign certificate
Good day, Please Help. 1. In PowerBI im trying to render the javascript sign certificate of jsrsasign, i only got it working via an html file. So im trying to read the html file, simple hello to start of with. Am i better going directly to do the jsrsasign? 2. Locally on VS i got the simple function to return Hello Azure, but trying to read the simple html file executes no error but if i copy in postman i just get a 401 no content found, im not sure how further to debug as in VS i get Ok status, Nothing in Console? Anybody have an example or links plz? const { app } = require('@azure/functions'); const fs = require('fs'); const path = require('path'); app.http('IC5', { methods: ['GET', 'POST'], authLevel: 'anonymous', handler: async (request, context) => { context.log(`Http function processed request for url "${request.url}"`); // const name = request.query.get('name') || await request.text() || 'world'; // return { body: `Hello, ${name}!` }; //var res = { //body: "", //headers: { //"Content-Type": "text/html" //} //}; // readFile = require('../SharedCode/readFile.js'); //filepath = __dirname + '/test3.html'; //fs = require('fs'); //await fs.readFile(filepath,function(error,content){ fs.readFile(path.resolve('./test3.html'), 'UTF-8', (err, htmlContent) => { context.res = { status: 200, headers: { 'Content-Type': 'text/html' }, body: htmlContent } }) // if (request.query.name || (request.body && request.body.name)) { // res.body = "<h1>Hello " + (request.query.name || request.body.name) + "</h1>"; //} else { //fs.readFile(path.resolve(__dirname,'test3.html'), 'UTF-8', (err, htmlContent) => { //res.body= htmlContent; //context.res = res; //}); // } } }); //TEST IN POSTMAN: http://localhost:7071/api/IC5?name=hurry402Views0likes1CommentUnable to trigger function app while using managed identity for the storage account connection
I am trying to create an Azure Function of BlobTrigger type, which needs to be triggered on dropping files in the storage account say filessa. Due to policy restriction the storage account cannot use shared access key. I am unable to trigger the function app dropping a file into a container. I see intermittently an error in the function app logs No valid combination of account information found. assembly : Azure.Storage.Blobs, Version=12.23.0.0, Culture=neutral, PublicKeyToken=9279e12e44c8 method : Azure.Storage.StorageConnectionString+<>c.<Parse>b__67_0 outerType : Microsoft.Azure.WebJobs.Host.Indexers.FunctionIndexingException outerMessage: Error indexing method 'Functions.SPAREventGridBlobTrigger' innermostMessage: No valid combination of account information found. I am referring to Configuring Azure Blob Trigger Identity Based Connection and have created the environment settings and assigned required roles to storage accounts (function App's storage account, say fnsa and the storage account which is used to upload the file to trigger the function app, filessa) as mentioned in this article. This is my simple code [Function(nameof(SPAREventGridBlobTrigger))] public async Task Run([BlobTrigger("samples-workitems/{name}", Source = BlobTriggerSource.EventGrid, Connection = "filessa_STORAGE")] Stream stream, string name) { using var blobStreamReader = new StreamReader(stream); var content = await blobStreamReader.ReadToEndAsync(); Console.WriteLine("Hello from Jey Jey Jey"); _logger.LogInformation($"C# Blob Trigger (using Event Grid) processed blob\n Name: {name} \n Data: {content}"); } I have assigned roles to the storage account filessa Storage Blob Data Owner and Storage Queue Data Contributor for the Azure Function identity. and assigned roles to the storage account fnsa Storage Blob Data Contributor for the Azure Function identity. (Actually I ended up adding many other roles like Storage Account Contributor, Storage Blob Data Reader and similar too to both storage accounts) Please advice me to on the items to be added in the environment settings. 1. the name and value of the connection of the storage account, filessa 2. the name and value of the connection of the storage account, fnsa 3. other items that needs to be mandatorily added to make it work I have tried added items like AzureWebJobsStorage, AzureWebJobsStorage__accountName, AzureWebJobsStorage__blobServiceUri, ..., AzureWebJobsfilessa_STORAGE, filessa_STORAGE. I have also referred to this microsoft documentation https://learn.microsoft.com/en-us/azure/azure-functions/functions-event-grid-blob-trigger?pivots=programming-language-csharp ; tried adding the EventSubscription in the storage account filessa. The webhook https://FA-SPAREG-FA.azurewebsites.net/runtime/webhooks/blobs?functionName=Host.Functions.SPAREventGridBlobTrigger&code=_MPRFuo9sdEg== in Postman with POST returned back error Please help me with all the required environment settings to be added in the function app in Azure and any other suggestion or steps I have missed here to make this work.188Views0likes1CommentRetrieving Azure App Service Deployment Center Events - Monitoring
Hello Team, I would like to know how to retrieve Azure App Service Deployment Center events. Specifically, I’m looking to integrate a webhook to capture trigger and deployment events from the Deployment Center. Thanks, Vinoth_Azure145Views0likes2CommentsGetting error message "Invoking Azure function failed with HttpStatusCode - Unauthorized"
I have a synapse pipeline which contains a single component, an azure function activity component. The objective is to send a test JSON payload to a private endpoint using POST call. The azure function activity is configured to use the POST method and an azure function linked service has also been specified in the activity. We have a function app in premium plan, the linked service is pointing to the function app. Inside the function app, we have function which contains the main python code that makes the request. Function app stack is python and the function created inside is an HTTP trigger using V2 programming model and the authorization level selected is Function. When I debug the pipeline I am getting the error message Invoking Azure function failed with HttpStatusCode - Unauthorized. Please support in resolving this. Thanks370Views0likes1CommentEnabling and disabling forwarding rule
Hello, We need to turn on a mail forwarding rule on a single mailbox, within 365. We looked at using a Azure Function App and copilot got us most of the way there but need some help with a 400 error. Failed to enable rule: The remote server returned an error: (400) Bad Request. The API authenticates and has the Mail.ReadWrite and Mail.Send and seems to be happy there. Is there a reason why this is giving a 400 error as all the details (I thought) were in order. # Azure AD App details $clientId = "your-client-id" $clientSecret = "your-client-secret" $tenantId = "your-tenant-id" # Function parameters $mailbox = "email address removed for privacy reasons" $ruleId = "086b4cfe-b18a-4ca0-b8a6-c0cc13ab963e3208025663109857281" # Provided rule ID without backslash # Get OAuth token $body = @{ client_id = $clientId client_secret = $clientSecret scope = "https://graph.microsoft.com/.default" grant_type = "client_credentials" } try { $response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body $token = $response.access_token Write-Output "Token acquired successfully." } catch { Write-Error "Failed to get OAuth token: $_" return } # Enable the existing rule $headers = @{ Authorization = "Bearer $token" ContentType = "application/json" } $body = @{ isEnabled = $true } try { $jsonBody = $body | ConvertTo-Json Write-Output "JSON Body: $jsonBody" $response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$mailbox/mailFolders/inbox/messageRules/$ruleId" -Method Patch -Headers $headers -Body $jsonBody Write-Output "Rule enabled successfully: $($response | ConvertTo-Json)" } catch { Write-Error "Failed to enable rule: $_" Write-Output "Response Status Code: $($_.Exception.Response.StatusCode)" Write-Output "Response Status Description: $($_.Exception.Response.StatusDescription)" if ($_.Exception.Response -ne $null) { $responseContent = $_.Exception.Response.Content.ReadAsStringAsync().Result Write-Output "Response Content: $responseContent" } else { Write-Output "No response content available." } } # Return response Write-Output "Script completed."Solved129Views1like3CommentsHow to solve issue: Incorrect worker runtime specified for function app (AZFD0013)?
Hi, (I apologize if this post is placed incorrectly within the community.) we've used app Start/Stop VMs during off hours - V2 (https://github.com/microsoft/startstopv2-deployments) (https://portal.azure.com/?websitesextension_ext=asd.featurePath%3Ddetectors%2FAppServiceAdvisorRecommendations&feature.tokencaching=true&feature.internalgraphapiversion=true#view/Microsoft_Azure_Marketplace/GalleryItemDetailsBladeNopdl/id/microsoftcorporation1620879115842.startstopv2/resourceGroupId//resourceGroupLocation//dontDiscardJourney~/false/_provisioningContext~/%7B%22initialValues%22%3A%7B%22subscriptionIds%22%3A%5B%22a486747b-a1bf-4aa3-aa6a-248af42392ec%22%5D%2C%22resourceGroupNames%22%3A%5B%5D%2C%22locationNames%22%3A%5B%22westeurope%22%5D%7D%2C%22telemetryId%22%3A%22fab7850d-5232-4cd6-a891-1d09c2b5c068%22%2C%22marketplaceItem%22%3A%7B%22categoryIds%22%3A%5B%5D%2C%22id%22%3A%22Microsoft.Portal%22%2C%22itemDisplayName%22%3A%22NoMarketplace%22%2C%22products%22%3A%5B%5D%2C%22version%22%3A%22%22%2C%22productsWithNoPricing%22%3A%5B%5D%2C%22publisherDisplayName%22%3A%22Microsoft.Portal%22%2C%22deploymentName%22%3A%22NoMarketplace%22%2C%22launchingContext%22%3A%7B%22telemetryId%22%3A%22fab7850d-5232-4cd6-a891-1d09c2b5c068%22%2C%22source%22%3A%5B%5D%2C%22galleryItemId%22%3A%22%22%7D%2C%22deploymentTemplateFileUris%22%3A%7B%7D%2C%22uiMetadata%22%3Anull%7D%7D) It worked without any issues, but 8.10 we received the notification described in the article: https://learn.microsoft.com/en-us/azure/azure-functions/errors-diagnostics/diagnostic-events/azfd0013. In the notification it was written: We have a new Functions recommendation for startstopvm23dvt65bpvxrmw Incorrect worker runtime specified for function app We've noticed that your function app (**startstopvm23dvt65bpvxrmw**) is configured with the FUNCTIONS_WORKER_RUNTIME setting as "dotnet-isolated", but expected value for the deployed application payload is "dotnet". This is an unoptimized state which limits performance and may impact application reliability. To help detect this, you may now see the AZFD0013 event raised at the Warning level in your logs. This will be raised to Error level in a future update. To ensure your app can run properly, for its current payload, you should set the FUNCTIONS_WORKER_RUNTIME value to "dotnet". You must also update any deployment automations you have, such as templates or CI/CD pipelines, so they specify the correct value as well. Please see https://aka.ms/functions-invalid-worker-runtime for more information. If I understand correctly, our FUNCTIONS_WORKER_RUNTIME is set to "dotnet-isolated", and we should reset it to "dotnet" But in the GitHub documentation I found: August 19, 2024 Start/Stop v2 has been migrated to the https://learn.microsoft.com/azure/azure-functions/functions-versions?tabs=isolated-process%2Cv4&pivots=programming-language-csharp#languages. https://github.com/microsoft/startstopv2-deployments?tab=readme-ov-file#upcoming-or-recent-updates-to-startstop-v2 When I checked the application settings in Azure, I also get this notification. When I look in the configuration, there it is set as it is written in GitHub - I assume this setting is correct When I look in the environment variables, and look for FUNCTIONS_WORKER_RUNTIME. So there is dotnet-isolated. But I don't know if by changing this variable, something will not work on dotnet, when the configuration is also set to .NET 8 Isolated? Can anyone advise me on how to proceed to eliminate this problem? Thanks for all the tips, tricks and advice TomSolved2.9KViews0likes2CommentsAzure Functions - Using durable functions in Python v2
Hey guys, i am new to azure functions. Maybe one expert can have a quick look at the code and give me some advice, since I really dont know whats going on. I want to use a simple durable function whith python v2 in vs code. I have the azure extensions, Azure functions core tools, etc. installed. I find it hard to read the documentation, I am missing more examples and explanations. I wrote the following example of reading a book. The Skript ist starting and I get logs, but it doesnt work as planed. The orchestrator function does start again at the top (not in the while loop). How it should work: http_start trigger: Starts the orchestrator function orchestrator function: Manages the book reading process activity function: flips the page import azure.functions as func import azure.durable_functions as df import logging.config import logging app = df.DFApp(http_auth_level=func.AuthLevel.ANONYMOUS) @app.orchestration_trigger(context_name="context") def orchestrator_reading_a_book(context: df.DurableOrchestrationContext): x = None book = "Example_book" page = 1 logging.warning(f'Your Book: {book} at page {page}') while page < 4: x = yield context.call_activity("flip_page", { "book": book, "page": page, }) book = x.get("book") page = x.get("page") logging.warning(f'Your Book: {book} at page {page}') logging.warning("You finished reading the book") return("You finished reading the book") @app.activity_trigger(input_name="context") def flip_page(context): if context: book = context["book"] page = context["page"] page += 1 logging.warning(f"You flipped the page to page {page}") return {"book": book, "page": page} # An HTTP-triggered function with a Durable Functions client binding @app.route(route="orchestrators/{functionName}") @app.durable_client_input(client_name="client") async def http_start(req: func.HttpRequest, client): function_name = req.route_params.get('functionName') instance_id = await client.start_new(function_name) response = client.create_check_status_response(req, instance_id) return response Thanks for the help in advance! Best regards!930Views0likes1Comment