Trying to make HttpTrigger pass a blob - c#

I'm trying to make a HTTP Trigger in Visual Studio Code which just need to make a file and pass it to blob storage, but I get an error saying: "The type or namespace 'Blob' could not be found"

Here is a full working example. I think you are just missing a using / referece a nuget package.
Reference Nuget package Microsoft.Azure.WebJobs.Extensions.Storage
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;
namespace SampleFunctions
{
public static class Http2BlobFunction
{
[FunctionName("Http2BlobFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
[Blob("myblobcontainer/{rand-guid}.txt", FileAccess.Write)] CloudBlockBlob blob,
ILogger log)
{
log.LogInformation("Received file upload request");
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
await blob.UploadTextAsync(requestBody);
return new OkObjectResult(blob.Name);
}
}
}

If you VS Code to develop Azure Function V2.0, you need to manually install package vai .NET.CLI. Since you use storage binding, please run the command dotnet add package Microsoft.Azure.WebJobs.Extensions.Storage --version 3.0.7 to install the package. For more details, please refer to the document.

You can also use the azure CLI to install extensions.
func extensions install
Finally, you can use the portal

Related

'No job functions found' .Net Azure Function after migration from Microsoft.Azure.WebJobs.ServiceBus to Microsoft.Azure.WebJobs.Extensions.ServiceBus

I am migrating some legacy .Net code from an App Service into an Azure Function triggered by a Service Bus topic. This will run under .Net Framework 4.8 as an Azure function V1. I am running into the error "No job functions found. Try making your job classes and methods public" etc.
To test this, I created a brand new Azure function using the Visual Studio 2022 template, and it does not have this warning. However, looking at the NuGet packages, I can see that the template installs Microsoft.Azure.WebJobs.ServiceBus, which is deprecated.
I removed that package and installed the new Microsoft.Azure.WebJobs.Extensions.ServiceBus package that is recommended.
The only change to the code that I had to make was to remove the AccessRights attribute, since that's not supported any more.
Now, when I run the Azure Function, I get the "No job functions found" warning.
The warning suggests that I am supposed to call config.UseServiceBus() somewhere. I've seen from some questions on this where people do this in Program.cs in the Main function. However, this is a DLL library project, so there is no Program.cs or startup code.
I've looked for a Migration Guide and searched for similar problems, but everything I've found is for .Net 5, not Framework 4.8.
What is the correct way to initialize a .Net48 Azure Function built as a DLL? Should I convert this project to a Console Program instead, and initialize in Main()?
Edit:
This is the template-generated function that works before updating the library:
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.ServiceBus.Messaging;
namespace AFTest
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("testtopic", "testsubscription", AccessRights.Listen, Connection = "ServiceBusConnectionString")]string mySbMsg, TraceWriter log)
{
log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
}
}
Here's the slightly modified code (removing the Access attribute) that doesn't work:
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace AFTest
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("testtopic", "testsubscription", Connection = "ServiceBusConnectionString")]string mySbMsg, TraceWriter log)
{
log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
}
}

WPF WebHostBuilder does not contain definition for UseKestrel

I am trying to implement single sign on using OIDC as per GitHub but I keep getting the error:
'WebHostBuilder' does not contain a definition for 'UseKestrel' and no accessible extension method 'UseKestrel' accepting a first argument of type 'WebHostBuilder' could be found (are you missing a using directive or an assembly reference?)
when implementing the SystemBrowser.cs code
using IdentityModel.OidcClient.Browser;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//other code
//simplified code extract below
IWebHost _host = new WebHostBuilder()
.UseKestrel()
.UseUrls(_url)
.Configure(Configure)
.Build();
//other code
According to this it should be part of the Microsoft.AspNetCore.Hosting?
Is there something I'm missing or a NuGet package I need installing? The packages installed so far are:
Any assistance would be appreciated.
The default asp.net core application could work well because the Microsoft.AspNetCore.Hosting package and other related package integrated in the framework.
I test a console application with asp.net core and reproduce your issue.Install the Microsoft.AspNetCore.Hosting together with Microsoft.AspNetCore.Server.Kestrel.
You could download on NuGet Package Manager by searching for the package name or download on Package Manager Console by using the command in the following reference:
https://www.nuget.org/packages/Microsoft.AspNetCore.Server.Kestrel/2.2.0?_src=template

Error with Azure Function and Docker

I am trying to implement the ICS creator sample for Azure Functions: https://github.com/Azure-Samples/azure-functions-create-ics-file-using-csharp-sample.
I followed all the steps there, but the difference with my implementation is that I'm running the function locally with Docker, and I am getting this error:
An unhandled exception occurred while processing the request.
CompilationErrorException: Script compilation failed.
Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker+d__26.MoveNext()
in DotNetFunctionInvoker.cs, line 313
FunctionInvocationException: Exception while executing function:
Functions.swinvite
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Per my understanding, the error is related with the ical.net library, that is not being imported to the image.
Any ideas?
Thank you in advance.
You are right, error is related to Ical.net library. You can try this repository.
More details
The guide you follow is to create function in function runtime 1.x(.net framework), where packages will be restored according to project.json. But you want to run using docker(image uses runtime 2.x, based on .net core), where project.json is invalid. So the file can be dropped.
Then we have to add Ical.Net related assemblies manually. We can download latest version package as the one in that guide is out of date.
After downloading the package, create a bin folder under ~\GetInvite. Copy Ical.Net.dll and NodaTime.dll(dependency of Ical.Net) to this folder.
And some changes in run.csx.
// add assembly
#r "Ical.Net.dll"
// remove some unnecessary namespaces
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Ical.Net;
using Ical.Net.DataTypes;
using Ical.Net.CalendarComponents;
using Ical.Net.Serialization;
// remove async as the method has no await method
public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log)
{
... // remain the same
// Event is deprecated in new version, use CalendarEvent
var icalevent = new CalendarEvent{...}
... // remain the same
}
One more point, in function.json change authLevel from function to anonymous. Or you will get 401 error.

ApiController could not be found

Based on this video https://www.youtube.com/watch?v=IVvJX4CoLUY I have add the using System.Web; using System.Web.Http; but i still get the error state that apicontroller could no found, and so on, below picture is the error I face:
below is my code :
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Collections.Generic;
namespace UploadToServer.Server.Controllers
{
public class UploadsController : ApiController
{
[Route("api/Files/Upload")]
public async Task<string> Post()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var filePath = HttpContext.Current.Server.MapPath("~/Uploads/" + fileName);
postedFile.SaveAs(filePath);
return "/Uploads/" + fileName;
}
}
}
catch (Exception exception)
{
return exception.Message;
}
return "no files";
}
}
}
Anyone can share me ideas?
You are missing the references in your project for those libraries. As per svdoever you can add the package Microsoft.AspNet.WebApi through NuGet to fix this. For instructions on how to use NuGet, please click here
Your question have nothing to do with Xamarin.Forms but with WEB.API. Your Xamarin.Forms project cannot and should not contain any WEB.Api controllers. Your server side code should be in a separate project. The easiest way to do so is to create a separate project with a specific template.Luckily Microsoft has a very easy to follow guides:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
However I would recommend you to use Asp.NET Core instead:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api
You getting this error because packages required to run API are not installed.
Manually you have to download this package from nuget.org.
Follow below steps -
Check whether Nuget.ORG listed in Package Source.
Tools -> Nuget Package Manager -> Package Manager Setting -> Package Sources.
If Nuget is not listed in Package Source then Add source as "http://nuget.org" and update.
Tools -> Nuget Package Manager -> Package Manager Console
Select Package source as "Nuget" and Click Restore
Same can be done by Right Click Your Solution file -> Manage Nuget Packages for solution.
Select Nuget in Package Source and restore.
Required packages will be downloaded from nuget.org

Cannot create an abstract class?

I'm trying to run firebase functions locally but I get the error:
Exception while executing function: Functions.TestMe. Microsoft.Azure.WebJobs.Host: One or more errors occurred. Exception binding parameter 'req'. mscorlib: Cannot create an abstract class.
I have an azure cloud function project in VSCode with just this function:
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Learning.Platform
{
public static class TestMe
{
[FunctionName("TestMe")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var db = new MongoClient(/*snipped*/);
var hey = db.GetDatabase("dude").GetCollection<object>("hey");
return (ActionResult)new OkObjectResult($"Hello, {hey}");
}
}
}
I would have thought this would just work because it's a fairly basic example of azure functions.
I'm using the Azure .net SDK version 2.9, Azure Tools 1.3.0 and the .Net Core 2.0 framework.
I gave up out of frustration and uninstalled the .net core framework and azure tools then reinstalled both.
Issue resolved itself.
For anyone who runs into this. I had the same issue, and was able to resolve it. I ran into this while trying to mess around and create an F# HttpTrigger function against v2 of the azure function runtime (since they don't have templates for that yet...).
Anyway, my issue was that I had installed the System.AspNetCore.Http Nuget package into my project while I was troubleshooting something else. After removing the reference to the Nuget package (Leaving only the Microsoft.NET.Sdk.Functions) it started working again.
There was an an issue within the azure storage assembly - i run in the same problem as i tried run a webjob - but the azure storage team fixed it

Categories

Resources