How to fix "No event hub receiver named <name>" - c#

I am writing an azure webjob which reads events from eventhub using NET Core 3.1.
I have a config file as below:
{
"JobHostConfig": {
"DashboardConnectionString": "",
"StorageConnectionString": "xx"
},
"EventHubConfig": {
"EventHubConnectionString": "xx",
"EventHubName": "xx",
"EventProcessorHostName": "xx",
"ConsumerGroupName": "xx",
"StorageConnectionString": "xx",
"StorageContainerName": "xx"
}
}
In the Main method, I call ConfigureServices method which looks something like:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory() + $"\\..\\..\\..\\ConfigFiles")
.AddJsonFile($"applicationConfig.json", optional: true, reloadOnChange: true)
.AddJsonFile($"applicationConfig.{environment}.json", optional: true, reloadOnChange: true);
Configuration = builder.AddEnvironmentVariables()
.Build();
services.AddSingleton<IConfigurationRoot>(Configuration);
services.AddSingleton<IConfiguration>(Configuration);
services.AddMvcCore();
services.AddSingleton(GetInstance<EventHubConfig>());
services.AddSingleton(GetInstance<JobHostConfig>());
I confirmed that at runtime configs are getting populated in Configuration only like this: Configuration["EventHubConfig:EventHubName"]. But I also debugged that environment variables have not been set and its value is null.
So when I do:
ProcessEvent([EventHubTrigger("%EventHubName%", ConsumerGroup = "%ConsumerGroupName%", Connection = "%ConnectionString%")] EventData eventData) I get that %EventHubName% is not resolved.
Also, when I hard-code the values of these then I get: No event hub receiver named.
Can someone suggest what is wrong with my registration?
Furthermore, I replaced the values with string in EventHubTrigger, and I get Value cannot be null. Parameter name: receiverConnectionString

When using %% format, you should use Custom binding expressions.
For more details, please refer to this answer.
Please let me know if you still have more issues about it.

Right click the appsettings.json file -> click propertities -> set the "Copy to output directory" to "copy if newer"
and the code should be
public static void Trigger([EventHubTrigger("my eventhub name",Connection = "EventHubConnectionString")] EventData message, ILogger logger)
{
string data = Encoding.UTF8.GetString(message.Body);
Console.WriteLine(data+";;xxx");
}
Make your appsettings.json simpler like
{
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.net",
"EventHubConnectionString": "Endpoint=sb://xxxx"
}

Related

IOptions configuration binding not working in dotnet-isolated function [duplicate]

I'm attempting to port an existing Functions app from core3.1 v3 to net5.0 I but can't figure out how to get the IOptions configuration pattern to work.
The configuration in my local.settings.json is present in the configuration data, and I can get to it using GetEnvironmentVariable. Still, the following does not bind the values to the IOptions configuration like it used to.
.Services.AddOptions<GraphApiOptions>()
.Configure<IConfiguration>((settings, configuration) => configuration.GetSection("GraphApi").Bind(settings))
The values are in the local.settings.json just as they were before:
"GraphApi:AuthenticationEndPoint": "https://login.microsoftonline.com/",
"GraphApi:ClientId": "316f9726-0ec9-4ca5-8d04-f39966bebfe1",
"GraphApi:ClientSecret": "VJ7qbWF-ek_Amb_e747nXW-fMOX-~6b8Y6",
"GraphApi:EndPoint": "https://graph.microsoft.com/",
"GraphApi:TenantId": "NuLicense.onmicrosoft.com",
Is this still supported?
What am I missing?
I had the same issue, but turns out that the json was not correctly formatted.
Just for reference, here it is how I configured it:
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
s.AddOptions<ApplicationSettings>().Configure<IConfiguration>((settings, configuration) =>
{
configuration.GetSection(nameof(ApplicationSettings)).Bind(settings);
});
})
.Build();
And here is an example of local.setting.json:
{
"IsEncrypted": false,
"Values": {
"ApplicationSettings:test": "testtest",
"ApplicationSettings:testtest": "test"
}
}

How to configure environment on webjobs sdk?

I have a dotnet console app using webjobs sdk and I´m not able to find how to get the configuration file correctly based on the environment. My code:
static void Main(string[] args)
{
var builder = new HostBuilder();
var environmentName = Environment.GetEnvironmentVariable("environment");
builder.ConfigureHostConfiguration(config =>
{
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
});
...
After that I create 2 files: appsettings.json and appsettings.Production.json. When I´m debugging, even with the variable set to production, I always get the appsettings.json values and not the appsettings.Production.json value. What Im doing wrong here?

Setting Azure Functions app's base directory wtih Azure Function app 2.x

I need to set a Azure Functions app's base directory to the azurewebjobsscriptroot like below, but got exception
var config = new ConfigurationBuilder()
.SetBasePath("%HOME%\site\wwwroot") //error
.AddJsonFile("Settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
System.ArgumentException : The path must be absolute. Parameter name:
root at
Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String
root,ExclusionFilters filters) at
Microsoft.Extensions.Configuration.FileConfigurationExtensions.SetBasePath(IConfigurationBuilder
builder,String basePath)
Azure function 2.x
VS 2017
ExecutionContext is null to non-function methods via IoC, alternative to ExecutionContext.FunctionAppDirectory
https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#azurewebjobsscriptroot
You probably want to expand the path first before using it. That way the environment variable(s) embedded in the string can be replaced with the equivalent value of the variable. Resulting in a valid base path for the configuration.
var AzureWebJobsScriptRoot = "%HOME%\site\wwwroot";
var expandedRootPath = Environment.ExpandEnvironmentVariables(AzureWebJobsScriptRoot);
var config = new ConfigurationBuilder()
.SetBasePath(expandedRootPath)
.AddJsonFile("Settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
Reference Environment.ExpandEnvironmentVariables(String) Method

I can no longer get the values from local.setting.json with Azure Function

I was able to get and use the values from local.setting.json using Environment.GetEnvironmentVariable("test1");
now it's like there is no way to get this file and his values. I only know that another developer that isn't in my team changed something and from then doesn't works anymore... (I can't understand what he changes that can be the problem)
Actually for testing I tried this:
var appSettings = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var b = appSettings["test1"];
var c = appSettings["test2"];
var d = Environment.GetEnvironmentVariable("test1", EnvironmentVariableTarget.Machine);
var e = Environment.GetEnvironmentVariable("test1", EnvironmentVariableTarget.User);
var f = Environment.GetEnvironmentVariable("test1", EnvironmentVariableTarget.Process);
var g = Environment.GetEnvironmentVariable("test1");
After this all the variables are null
The local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"test1": "abcd",
"test2": "efgh"
}
}
I'm using visual studio 2017 and the project is Azure Functions, the file local.settings.json it's at the same level of the function.cs.
What could be?
Thank you!
Try the following:
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", true, true)
.Build();
It may be the case that your context.FunctionAppDirectory may be incorrect. Please also right click the config file -> Configuration -> Advanced => set Copy to output directory to Copy If Newer.
In my case, the contents of the local.settings.json are read by the IConfigurationBuilder however, for some reason they're not loaded on the Environment variables list (Environment.GetEnvironmentVariables()) so the Environment.GetEnvironmentVariable will never read them. So I'm in my Startup class, I manually attached the variables to the current process.
Here's my local.settings.json
{
"Values" : { "Region": "southeastasia" }
}
In my Startup class, here's my IConfigurationRoot:
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables().Build();
And here's how I attached them to the process:
Environment.SetEnvironmentVariable("Region", configuration.GetValue<string>("Values:Region"), EnvironmentVariableTarget.Process);
Now your Environment.GetEnvironmentVariable should look like this:
string region = Environment.GetEnvironmentVariable("Region", EnvironmentVariableTarget.Process);

.net core 2.0 tests - how to store settings in test projects?

I need to store connection strings and other settings in my .NET Core 2.0 integration tests (so, it's a Test project, with xUnit). How can I do this safely considering those tests run locally and in VSTS? Ideally, I need those settings separate for local environment and running on VSTS.
You can add multiple configuration files, such as appsettings.json, appsettings.dev.json, appsettings.test.json, then set the dev value for related environment variable and set test value for related variable of build.
After that replace the value in appsettings.test.json file through Token Replace task
Simple steps:
Install Microsoft.Extensions.Configuration.Json package to your xUnit test project
Add appsettings.json, appsettings.dev.json and appsettings.test.json configuration files to project
appsettings.json:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
},
"OtherSettings": {
"UserName": "name1",
"Pass": "pass1"
}
}
appsettings.dev.json:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=dev;Trusted_Connection=True;"
},
"OtherSettings": {
"UserName": "devname1",
"Pass": "pass1"
}
}
appsettings.test.json:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=#{testDev}#;Trusted_Connection=True;"
},
"OtherSettings": {
"UserName": "#{testName}#",
"Pass": "pass1"
}
}
Set Copy to Output Directory property of these files to Copy if newer.
4: Simple test code
:
[Fact]
public void Test1()
{
var envVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
Console.WriteLine($"env: {envVariable}");
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{envVariable}.json", optional: true)
.Build();
var conn = config.GetConnectionString("BloggingDatabase");
var otherSettings = config["OtherSettings:UserName"];
Console.WriteLine(conn);
Console.WriteLine(otherSettings);
}
Add ASPNETCORE_ENVIRONMENT (value: test), testDev and testName variables to build definition, you can click the lock icon to change variable type to secret.
Add Replace Tokens task before build task (Target files: **\appsettings.test.json)

Categories

Resources