ServiceBusTrigger not found in basic Azure Function project - c#

I have created a brand new .NET Core 3.1 Azure Function project using the Visual Studio template
I am using V3 of the functions, i.e. the version created by the template
I have the latest VS - 16.10.2
Straight away, it fails with ServiceBusTrigger and Connection not found?
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace AzureFunctionTest
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("AzureFunctionTest", "Research Subscription", Connection = "eventbus-connection")]string mySbMsg, ILogger log)
{
log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
}
}
Really strange how a template from MS itself does not work and a bit concerning this fails on the first hurdle!!
Here are the relevant parts of my project file
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Messaging.ServiceBus" Version="7.1.2" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
</ItemGroup>
Azure.Messaging.ServiceBus seems to be the latest package and the one recommended to use
What am I missing?
Paul

You should be using Microsoft.Azure.WebJobs.Extensions.ServiceBus package. Link.
You can read this official documentation for further information.

Related

Issue when creating a new ASP.NET Core 6.0 Web API

I tried to create a new Web API in ASP.NET Core 6.0 as shown https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-6.0&tabs=visual-studio-code#create-a-web-project.
But it is created with errors.
This is the WeatherForecastController of my new project:
using Microsoft.AspNetCore.Mvc;
// see here This is ends with ";". And showing this error "{ expected [TodoApi]"
namespace TodoApi.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
// some code
}
And the WeatherForecast class looks like this
// see here This is ends with ";". And showing this error "{ expected [TodoApi]"
namespace TodoApi;
public class WeatherForecast
{
// some code
}
And all namespaces are missing.
program.cs file looks like this; it does not have any namespace when created:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//.......
And TodoApi.GlobalUsings.g.cs file also has errors
// <auto-generated/>
global using global::Microsoft.AspNetCore.Builder;
global using global::Microsoft.AspNetCore.Hosting;
global using global::Microsoft.AspNetCore.Http;
global using global::Microsoft.AspNetCore.Routing;
global using global::Microsoft.Extensions.Configuration;
global using global::Microsoft.Extensions.DependencyInjection;
global using global::Microsoft.Extensions.Hosting;
global using global::Microsoft.Extensions.Logging;
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Net.Http.Json;
global using global::System.Threading;
global using global::System.Threading.Tasks;
The output of dotnet --info is
.NET SDK (reflecting any global.json):
Version: 6.0.100
Commit: 9e8b04bbff
Runtime Environment:
OS Name: ubuntu
OS Version: 20.04
OS Platform: Linux
RID: ubuntu.20.04-x64
Base Path: /snap/dotnet-sdk/147/sdk/6.0.100/
Host (useful for support):
Version: 6.0.0
Commit: 4822e3c3aa
.NET SDKs installed:
6.0.100 [/snap/dotnet-sdk/147/sdk]
.NET runtimes installed:
Microsoft.AspNetCore.App 6.0.0 [/snap/dotnet-sdk/147/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 6.0.0 [/snap/dotnet-sdk/147/shared/Microsoft.NETCore.App]
To install additional .NET runtimes or SDKs:
https://aka.ms/dotnet-download
But if I create an ASP.NET Core 3.1 project, it does not show these errors (I installed ASP.NET Core 3.1 to create ASP.NET Core 3.1 Web API).
I don't know why these errors occurs when creating a new ASP.NET Core 6.0 Web API project.
Does anyone know ?
Edit : I am using visual studio code.
and
TodoApi.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
</Project>
There are several new features of C# at play here.
First of all in Program.cs the Program class is "missing" because of a new feature called "Top level programs".
https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/#top-level-programs
The missing namespaces are because of "Global and implicit usings" which give you some standard namespaces included globally.
https://devblogs.microsoft.com/dotnet/announcing-net-6/#global-using-directives
As for the namespace with a semicolon after that is a "File scoped namespace" which is the same as wrapping the whole file in a namespace but without needing to indent everything.
https://devblogs.microsoft.com/dotnet/announcing-net-6/#file-scoped-namespaces
If you are using Visual Studio 2019 you will need to update to Visual Studio 2022 to use all these features. VSCode should automaticly update the C# extension to the latest version but if it hasn't (or you have disabled automatic updates) you might need to update it manually.
https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp

Identity asp.net core 3.0 - IdentityDbContext not found

My app broke with the 3.0 release of .NET core with reference errors for IdentityDbContext. I'm looking through documentation for Identity on core 3.0 but it implies that IdentityDbContext should be there. It's the only error I'm getting with a couple DbContext errors.
I have a pretty simple API, no MVC views, just a data server that gives back JSON objects. It's based on Identity so it has the users and roles and claims. And it's starting to take advantage of that. My main DbContext extends IdentityDbContext<ApplicationUser> but after switching target platform to 3.0 after the upgrade, it says it doesn't exist and gives me compile errors. Has anyone run into this? Am I missing something? The migration and breaking changes pages don't seem to have anything addressing my issue.
DbContext looks like this:
using System;
using Microsoft.AspNetCore.Identity;
//using Microsoft.AspNetCore.Identity.EntityFrameworkCore; <- this no longer works either
using Microsoft.EntityFrameworkCore; //<- this I had to download as a package
using App.Constants;
using App.Models.Identity;
namespace App.Models
{
public class AppContext : IdentityDbContext<ApplicationUser> //<- error is right here
{
... my models
}
}
In ASP.NET Core 3.0, Entity Framework Core and Identity related packages have been removed from the Microsoft.AspNetCore.App metapackage. So you have to add those packages separately.
Add the following PackageReferences to your project's .csproj file as follows:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0" />
</ItemGroup>
Now it will work!
For more details: Assemblies removed from the ASP.NET Core shared framework
if you have an error like "error CS0246: The type or namespace name 'IdentityDbContext' could not be found"
you can install bellow package for asp.net web api 3 project
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore --version 5.0.0-preview.3.20215.14
in dotnet cli.its work for me.
Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore -Version 5.0.0-preview.3.20215.14
this for package manager

Azure function local development in VS cannot find function

I'm currently developing a function app using Microsoft's Azure functions in Visual Studio. I am able to deploy and publish the functions on azure and it seems to run but whenever I try to run a function local the Hosting Environment is unable to find any "Jobs". I have included a picture below.
It must be stated that I was at some point able to deploy locally but I believe after some updates, I was unable to run my functions
The current version of Azure Function and Web Jobs Tools: 15.0.40424.0
I have tried to use Azure Functions V1 (.NET Frameworks) and Azure Functions V2 (.NET Core) when I create a new project but with unsuccessful results. I have also tried to create a new clean project, reinstall VS and also reset Windows in case of any strange setup.
Am I missing something and do I explicitly need state my functions somewhere such that the hosting environment can find them??
Hosting environment not finding any functions:
[6/20/2018 7:24:37 AM] Host configuration file read:
[6/20/2018 7:24:37 AM] {}
[6/20/2018 7:24:37 AM] Starting Host (HostId=2017noy-1005193785,
InstanceId=c8332a19-7eb3-4446-9b3e-4307f20a57bc, Version=2.0.11651.0,
ProcessId=15184, AppDomainId=1, Debug=False, ConsecutiveErrors=0,
StartupCount=1, FunctionsExtensionVersion=)
[6/20/2018 7:24:38 AM] Generating 0 job function(s)
[6/20/2018 7:24:38 AM] No job functions found. Try making your job classes
and methods public. If you're using binding extensions (e.g. ServiceBus,
Timers, etc.) make sure you've called the registration method for the
extension(s) in your startup code (e.g. config.UseServiceBus(),
config.UseTimers(), etc.).
Template Empty HTTPTrigger Function - Function1.cs:
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;
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static IActionResult
Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route =
null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = new StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query
string or in the request body");
}
}
}
CSPROJ File
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.13"
/>
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true"
}
}
The function.json file is generated after VS build. Check whether it's in a folder named after your function, under ~\bin\Debug\netstandard2.0 folder.
If you don't see the folder like Function1(containing function.json inside), you may have met the same problem my colleague has.
Didn't find the rout cause, VS just failed to generate function.json on my colleagues's computer, but on my side things works fine(VS and Azure Function and Web Jobs Tools has the same version).
The workaround we found is to downgrade Microsoft.NET.Sdk.Functions to 1.0.12.
Just for your reference, we have also tried upgrading Azure Function and Web Jobs Tools and delete Microsoft.NET.Sdk.Functions in C:\Users\UserName\.nuget\packages\microsoft.net.sdk.functions\1.0.13 and install this package again.
Update
Upgrade Microsoft.NET.Sdk.Functions to latest version of 1.0.14 also works on our side.
I had a same issue but I have downgrade Microsoft.NET.Sdk.Functions from version 3.0.11 to 3.0.10 and then start a program and it has shown all my functions in the console application once the program successfully runs I have upgraded to the previous function 3.0.11 it worked.

EF Core 2.0.0 and Redis.Core 1.0.3 don't work together

I tried to setup a .net core console application which uses EF core 2.0.0 and Redis.Core 1.0.3 (both are the current latest version).
Unfortunately if you try to put both into one application it won't even start. Even if you try to set a breakpoint right at the beginning or start debugging with Step into or Step Over doesn't help. All you get is this:
I think there happens some kind of type load exception or something similar. So far to reproduce the problem is quite easy with this project:
Project File (MyProject.csproj)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Redis.Core" Version="1.0.3" />
</ItemGroup>
</Project>
Application (Program.cs)
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Options;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
var cache = new RedisCache(Options.Create(new RedisCacheOptions()));
}
}
}
Anybody an idea or solution?
The problem is that
Microsoft.Extensions.Caching.Redis.RedisCache 1.0.3 depends on Microsoft.Extensions.Caching.Abstractions 1.0.3
Microsoft.EntityFrameworkCore 2.0.0 depends on Microsoft.Extensions.Caching.Abstractions 2.0.0
If you look at the Output Window, you will get:
TypeLoadException: Method GetAsync in type
Microsoft.Extensions.Caching.Redis.RedisCache from assembly
'Microsoft.Extensions.Caching.Redis, Version=1.0.3.0, Culture=neutral,
PublicKeyToken=adb9793829ddae60' does not have an implementation.
So: either wait until RedisCache gets updated to 2.0.0 or use EntityFrameworkCore < 2.0.0

C# .NET standard 1.6 with excessive dependencies in published application

I am trying out Visual Studio 2017 and .NET Core in what is my first attempt at C#/.NET in a few years (returning from Golang). I tried to create a small hello world style networking application that just listens and echos the input from tcp clients:
using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace TaskSockets
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
TcpListener server = new TcpListener(IPAddress.Any, 5555);
server.Start();
while (true)
{
TcpClient newClient = server.AcceptTcpClientAsync().Result;
Task.Run(async () => {
StreamWriter sWriter = new StreamWriter(newClient.GetStream(), Encoding.ASCII);
StreamReader sReader = new StreamReader(newClient.GetStream(), Encoding.ASCII);
Boolean bClientConnected = true;
String sData = null;
while (bClientConnected)
{
sData = await sReader.ReadLineAsync();
Console.WriteLine("Client: " + sData);
}
});
}
}
}
}
My project/build config looks like the following:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netstandard1.6</TargetFramework>
<RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.1.1" />
<PackageReference Include="Microsoft.NETCore.DotNetHostPolicy" Version="1.1.0" />
</ItemGroup>
</Project>
After publishing the application (dotnet publish) I get a folder with the executable I need. The problem I encounter, however, is that the folder contains 205 files (mostly .NET related DLL files) and is more than 30 MB in size. This includes dll files with reference to .NET libraries I don't even use such as System.Xml and Linq.
Is there any way to reduce the number of files and size of the published application so that just what I need is included?
UPDATE:
Tried to re-create the project from scratch using the dotnet tool rather than visual studio:
dotnet new console --language C# --name Socket --output Socket
--framework netcoreapp1.0
This created this project (which for some reason compiles to a dll despite the exe output type and console application target):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.0</TargetFramework>
</PropertyGroup>
</Project>
Then manually modify the csproj file so it looks like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.0</TargetFramework>
<RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.0.6" />
</ItemGroup>
</Project>
Now publish with:
dotnet publish --runtime win7-x64 --configuration Release
And go to:
./bin/Release/netcoreapp1.0/win7-x64
Now suddenly there is a working exe-file and just a few DLL files that is approximately 1 MB in size. By deleting the subfolder called "publish" I now have something that works without most of the bloat. No idea why this worked and if its considered expected behavior. No idea what the publish folder is for either or whether or not its needed for deployment on a computer without .NET installed. Microsoft have some work to do on its documentation.
Have a look at https://learn.microsoft.com/en-us/dotnet/articles/core/deploying/index
In the 1st case, your publish command generates output for a Framework-dependent deployment that is relying on the presence of the .NET Core framework on the target machine. Your code (in the form of dll(s)) will be executed by the runtime.
In the 2nd case, when you specify the target runtime using the --runtime option, publish generates output for a Self-contained deployment in which the used version of the .NET Core framework is included. There's a way to reduce the total size of the output as described in the above mention article in the Deploying a self-contained deployment with a smaller footprintsection.
As for why <OutputType>Exe</OutputType> didn't generate a exe-file, check out https://learn.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-build
It basically says the generated
binaries include the project's code in Intermediate Language (IL)
files with a .dll extension
and that the difference between specifying and not specifying <OutputType>Exe</OutputType>
is that the IL DLL for a library doesn't contain entry points and
can't be executed.

Categories

Resources