I'm trying to read secrets from a Azure Key Vault in my azure function c# script, but I'm facing an error
I already create a function.proj file with content below
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.6.0" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.3.0" />
</ItemGroup>
</Project>
I enabled the System assigned from my Function App and it created a Object Id number.
Then copied this number and added it to my Key Vault Access policies at Select principal option and choose Get and List for Secret Permissions
When I try this code below:
string keyVaultUri = "https://my-vault-test.vault.azure.net/";
var client = new SecretClient(new Uri(keyVaultUri), new DefaultAzureCredential());
var secret = client.GetSecret("first-secret");
error:
2022-05-04T16:41:51.383 [Error] Executed 'Functions.myFff' (Failed,
Id=number..., Duration=574ms) Method not found: 'Void
Azure.Core.TokenRequestContext..ctor(System.String[], System.String,
System.String, System.String)'.
I changed the versions of the packages and it worked well...
1.5.0 for Azure.Identity
4.2.0 for Azure.Security.KeyVault.Secrets
Related
I am trying to run install and run Azure PowerShell modules in C# and invoke the script.
Installing Azure PowerShell modules called from C# .net6.0 is doable. This is from the Microsoft PowerShell team:
https://github.com/PowerShell/PowerShellGet/blob/master/test/perf/benchmarks/BenchmarksV3RemoteRepo.cs
So I created a simple C# code to reproduce it.
using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
// Setting up the PowerShell runspace
var defaultSS = InitialSessionState.CreateDefault2();
defaultSS.ExecutionPolicy = ExecutionPolicy.Unrestricted;
var pwsh = PowerShell.Create(defaultSS);
// Import the PSGet version we want to test
pwsh.AddScript(#"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
Import-Module PowerShellGet -RequiredVersion 3.0.14 -Force");
var result = pwsh.Invoke();
foreach (var outputItem in result) Debug.WriteLine(outputItem);
pwsh.Commands.Clear();
pwsh.AddScript("Install-PSResource -Name Az -Repository PSGallery -TrustRepository -Reinstall");
var results = pwsh.Invoke();
foreach (var outputItem in results) Debug.WriteLine(outputItem);
csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.Commands.Diagnostics" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Commands.Management" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Commands.Utility" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.ConsoleHost" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.CoreCLR.Eventing" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Native" Version="7.3.0"/>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.2.7"/>
<PackageReference Include="Microsoft.PowerShell.Security" Version="7.2.7"/>
<PackageReference Include="System.Management.Automation" Version="7.2.7"/>
</ItemGroup>
</Project>
Errors:
The specified module 'PowerShellGet' with version '3.0.14' was not loaded because no valid module file was found in any module directory.
The term 'Install-PSResource' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
To view the error buffer inspect the powershell.ErrorBuffer.Result value
I have reproduced in my environment and I have faced similar error as below:
Then I have used the below command:
Install-Module -Name PowerShellGet -RequiredVersion 3.0.14-beta14 -AllowPrerelease -Force
By using the above command my error got resolved.
I have developed an Azure Function v4 with .net 6.0. It contains only http triggered functions.
Locally everything works fine, but after deploying it to Azure i only get 500 Status Code by calling any endpoint and it always throws InvalidOperationException at Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcFunctionInvocationDispatcherLoadBalancer.GetLanguageWorkerChannel : Did not find any initialized language workers
Application settings
Operating System: Windows
Runtime Version: 4.0.1.16815
Location: West Europe
Update Add more information
Project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" OutputItemType="Analyzer" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"StorageConnectionString": "UseDevelopmentStorage",
"APPINSIGHTS_INSTRUMENTATIONKEY": "MyInstrumentationKey"
},
"Host": {
"LocalHttpPort": 7071,
"CORS": "*"
}
}
One of the workaround to resolve this issue:
Created Azure Functions (Stack: .Net 6 Isolated) in Visual Studio and run locally:
After deploying of Function App in the Azure Portal (Stack: .Net 6, Location: West Europe, OS: Windows, Plan: Consumption, Function Runtime: Isolated)
This is the configuration:
After deploying, the function URL is running successfully:
As I can see a setting called WEBSITE_NODE_DEFAULT_VERSION is added into your .Net Function App Configuration Settings.
If your function is not created with node.js and if you are not using this application setting explicitly in your code then you can remove this property from your function app. This is stated in this MSFT Q&A.
The other reasons for this kind of error would be
The Functions Runtime is initialized but it failed to initialize the Language Worker. So, the Functions Runtime detects that the worker channel has not started and logs the error message on further invocations.
Note:
5. Try Re-creation of the Function App (.Net 6 - Windows OS- West Europe Location) in the Azure Portal and deploy your HTTP Trigger Function from Visual Studio.
Or
6. Try removing the WEBSITE_NODE_DEFAULT_VERSION setting > Save > Restart the app in the azure portal and run the function.
7. Make sure this setting is "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated" in your function app local.settings.json file.
8. This error may exist due to unmatching of Functions worker version and SDK version. If any updates available, please update them through NuGet Packet Manager:
Also, this error exist in previous version of dotnet Isolated is 5 and in Azure Functions Version V3.
References:
azure-functions-dotnet-worker/issues
https://github.com/Azure/azure-functions-host/issues/7618.
SO Thread1
I can create a new dotnetcore app that has authentication/identity using the command line:
dotnet new mvc --auth Individual
How can i include entity framework in the project also?
TL;DR
You already have it in your project
Long form answer
After creating your application, it should have Entity Framework as a dependency. I'm assuming that you're running the .NET Core 2.0 SDK.
Here's the output from my machine
$ dotnet new mvc --auth Individual --name testForStackOverflow
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.
Processing post-creation actions...
Running 'dotnet restore' on testForStackOverflow/testForStackOverflow.csproj...
Restoring packages for testForStackOverflow/testForStackOverflow.csproj...
Restore completed in 40.17 ms for testForStackOverflow/testForStackOverflow.csproj.
Restore completed in 40.17 ms for testForStackOverflow/testForStackOverflow.csproj.
Restore completed in 25.25 ms for testForStackOverflow/testForStackOverflow.csproj.
Generating MSBuild file testForStackOverflow/obj/testForStackOverflow.csproj.nuget.g.props.
Generating MSBuild file testForStackOverflow/obj/testForStackOverflow.csproj.nuget.g.targets.
Restore completed in 2.84 sec for testForStackOverflow/testForStackOverflow.csproj.
Restore succeeded.
I then look a look at the csproj which was generated:
$ cd testForStackOverflow/
~/testForStackOverflow$ ls
app.db Data Startup.cs
appsettings.Development.json Extensions testForStackOverflow.csproj
appsettings.json Models Views
bower.json obj wwwroot
bundleconfig.json Program.cs
Controllers Services
~/testForStackOverflow$ cat testForStackOverflow.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<UserSecretsId>aspnet-testForStackOverflow-AD382505-1A70-4A75-8059-1E0E3897A088</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<None Update="app.db" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
The important line of the csproj is here:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
This is a reference to the ASP.NET Core metapackage. This package contains all of the common ASP.NET Core NuGet packages, including Entity Framework Core - as per this screen shot from NuGet (captured a few moments ago)
This means that part of the package restore operation included restoring EF Core into your project.
I would say that you should take a look at this documentation for EF Core - the link should take you directly to the section labelled "The Model". You don't need the stuff in the preceding section (labelled "Get Entity Framework Core") as you already have it.
Of course, if you're using version 1.x of the .NET Core SDK, then it's a slightly different story.
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
I have following projects on solution and this works perfectly fine on my local.
However when I check code in Team service and create build it fails.
mainconsole.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
<PackageTargetFallback>portable-net45+win8</PackageTargetFallback>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.Portable.Compatibility" Version="1.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\business\business.csproj" />
<ProjectReference Include="..\portableextensibility\portableextensibility.csproj" />
<ProjectReference Include="..\portablelibrary\portablelibrary.csproj" />
</ItemGroup>
</Project>
Build tasks:
command line - tool dotnet, argument - restore
command line - tool dotnet, argument - build
Build fails:
d:\a\3\s\portablelibrary\portablelibrary.csproj(43,3): error MSB4019: The imported project "C:\Program Files\dotnet\sdk\1.0.4\Microsoft\Portable\v4.5\Microsoft.Portable.CSharp.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.
d:\a\3\s\portableextensibility\portableextensibility.csproj(42,3): error MSB4019: The imported project "C:\Program Files\dotnet\sdk\1.0.4\Microsoft\Portable\v4.5\Microsoft.Portable.CSharp.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.
C:\Program Files\dotnet\sdk\1.0.4\NuGet.targets(97,5): error : Unable to resolve 'd:\a\3\s\portableextensibility\portableextensibility.csproj' for '.NETCoreApp,Version=v1.1'. [d:\a\3\s\dotnetcompatibility.sln] C:\Program Files\dotnet\sdk\1.0.4\NuGet.targets(97,5): error : Unable to resolve 'd:\a\3\s\portablelibrary\portablelibrary.csproj' for '.NETCoreApp,Version=v1.1'. [d:\a\3\s\dotnetcompatibility.sln] Generating MSBuild file d:\a\3\s\mainconsole\obj\mainconsole.csproj.nuget.g.props. Generating MSBuild file d:\a\3\s\mainconsole\obj\mainconsole.csproj.nuget.g.targets. Writing lock file to disk. Path: d:\a\3\s\mainconsole\obj\project.assets.json Restore failed in 37.7 sec for d:\a\3\s\mainconsole\mainconsole.csproj.
Errors in d:\a\3\s\business\business.csproj
Unable to resolve 'd:\a\3\s\portablelibrary\portablelibrary.csproj' for '.NETStandard,Version=v1.1'.
Errors in d:\a\3\s\mainconsole\mainconsole.csproj
Unable to resolve 'd:\a\3\s\portableextensibility\portableextensibility.csproj' for '.NETCoreApp,Version=v1.1'.
Unable to resolve 'd:\a\3\s\portablelibrary\portablelibrary.csproj' for '.NETCoreApp,Version=v1.1'.
Since the solution contains PCL libraries which currently cannot be built using the dotnet cli, the project has to be built through msbuild instead of the dotnet based commands.
Here is the corrected configuration:
Build Definition
Queue options
Result