I'm starting out using Azure and c# and I'm attempting to use Table Storage - and using an Azure Function to update entitys in the table. My code is as follows:
#r "Microsoft.WindowsAzure.Storage"
#r "Newtonsoft.Json"
using System;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
public static async Task<HttpResponseMessage> Run(HttpRequest req, CloudTable lookupTable)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string partitionKey = data.Society;
string rowKey = data.ConnectionDetails.Environment;
string newConnection = data.ConnectionDetails.Connection;
TableOperation operation = TableOperation.Retrieve<SocietyConnectionDetails>(partitionKey, rowKey);
TableResult result = lookupTable.Execute(operation);
SocietyConnectionDetails societyConnectionDetails = (SocietyConnectionDetails)result.Result;
societyConnectionDetails.Connection = newConnection;
operation = TableOperation.Replace(societyConnectionDetails);
lookupTable.Execute(operation);
}
public class SocietyConnectionDetails : TableEntity
{
public string Connection {get; set;}
}
But the errors im getting are as follows:
2020-02-25T10:33:16.956 [Error] run.csx(17,38): error CS1061: 'CloudTable' does not contain a definition for 'Execute' and no accessible extension method 'Execute' accepting a first argument of type 'CloudTable' could be found (are you missing a using directive or an assembly reference?)
2020-02-25T10:33:16.984 [Error] run.csx(22,17): error CS1061: 'CloudTable' does not contain a definition for 'Execute' and no accessible extension method 'Execute' accepting a first argument of type 'CloudTable' could be found (are you missing a using directive or an assembly reference?)
2020-02-25T10:33:17.011 [Error] run.csx(8,47): error CS0161: 'Run(HttpRequest, CloudTable)': not all code paths return a value
I can see that the issue is happening when im attempting to 'Execute' my Table Operations... this might be a relatively straight forward problem but I'm struggling to work out why this wouldn't be working...
Thanks for any help..
I can reproduce your error.
Like this:
Solution is add a function.proj file to your function.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
</ItemGroup>
</Project>
Then the error should disappear.
(If you dont do this. the compilation step will not success.)
I assume you are using the Azure Functions runtime 2, and in this case the problem is related to your references. You should reference the nuget package Microsoft.Azure.WebJobs.Extensions.Storage and ensure it is installed in your function, according to this article in Microsoft's documentation.
Related
When my project was using
<TargetFramework>netcoreapp3.1</TargetFramework>
I could get the localization injected in my page constructor:
IStringLocalizer<Strings> _localizer;
public IndexModel(IStringLocalizer<Strings> localizer) {
_localizer = localizer;
}
but still retrieve an alternative language's collection of strings:
var localizer = _localizer.WithCulture(new CultureInfo(cultureCode));
var translatedStr = localizer[c.Value].ToString();
Being in the process of upgrading to:
<TargetFramework>net6.0</TargetFramework>
The _localizer.WithCulture code shows this error in VS Code:
'IStringLocalizer<Strings>' does not contain a definition for 'WithCulture' and no accessible extension method 'WithCulture' accepting a first argument of type 'IStringLocalizer<Strings>' could be found (are you missing a using directive or an assembly reference?)
What is the dotnet 6 version of this?
If I switch back to netcoreapp3.1 I can clearly see the warning:
'IStringLocalizer.WithCulture(CultureInfo)' is obsolete: 'This method is obsolete. Use `CurrentCulture` and `CurrentUICulture` instead.'
But what are the CurrentCulture and CurrentUICulture it is referring to?
I am getting following errors:
Code:
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(redirectUrl)).Result;
Error:
An object reference is required for the non-static field, method, or property 'AuthenticationParameters.CreateFromResourceUrlAsync(Uri)' Pending email for Authorizers C:\Users\handemv\source\Workspaces\Dynamics 365\Trunk-UCI\Tools\Automation_CapGSupport\Pending Email\Pending email for Authorizers\PendingEmailCheck.cs
Code:
AuthenticationContext authContext = new AuthenticationContext(_authority, false);
AuthenticationResult result = authContext.AcquireToken(_serviceUri, clientCred);
Error:
AuthenticationContext' does not contain a definition for 'AcquireToken' and no accessible extension method 'AcquireToken' accepting a first argument of type 'AuthenticationContext' could be found (are you missing a using directive or an assembly reference?)
Can anyone help me for same?
Error : AuthenticationContext' does not contain a definition for 'AcquireToken' and no accessible extension method 'AcquireToken' accepting a first argument of type 'AuthenticationContext' could be found (are you missing a using directive or an assembly reference?)
Solution 1:
This error due to AcquireToken was removed in v3 of the Microsoft.IdentityModel.Clients.ActiveDirectory library.
To fix this downgrade the version in nuget to 2.22.302.111727 to solve this error.
Solution 2:
In V3 of ADAL.NET which appears to no longer have AcquireToken().
But it still has AcquireTokenAsync(). Note however that the parameters have slightly changed in the methods for v2 and v3.
For more details refer this thread
Error: An object reference is required for the non-static field, method, or property 'AuthenticationParameters.CreateFromResourceUrlAsync(Uri)' Pending email for Authorizers
Follow this link :https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/1410
I have ASP.Net MVC application, one part of it is compiling razor views to string. The code is very similar to this example:
https://long2know.com/2017/08/rendering-and-emailing-embedded-razor-views-with-net-core/
I registered Razor engine in Startup.cs in this way:
var viewAssembly = typeof(HtmlGeneratorService).GetTypeInfo().Assembly;
var fileProvider = new EmbeddedFileProvider(
viewAssembly,
"ApplicationServices.Widgets.Html.Templates");
services.Configure<MvcRazorRuntimeCompilationOptions>(options => {
options.FileProviders.Clear();
options.FileProviders.Add(fileProvider);
});
services.AddRazorPages().AddRazorRuntimeCompilation();
In test project i have this setup:
var builder = new HostBuilder()
.ConfigureWebHost(webHost =>
{
webHost.UseTestServer();
webHost.UseStartup<Startup>();
});
var host = await builder.StartAsync();
HttpClient = host.GetTestClient();
But when i call my endpoint using this HttpClient, IRazorViewEngine.GetView starts to throw strange exceptions:
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.CompilationFailedException: 'One or more compilation failures occurred:
rnouw0xu.21w(4,41): error CS0234: The type or namespace name 'Razor' does not exist in the namespace 'Microsoft.AspNetCore' (are you missing an assembly reference?)
rnouw0xu.21w(4,82): error CS0518: Predefined type 'System.Type' is not defined or imported
rnouw0xu.21w(4,110): error CS0518: Predefined type 'System.String' is not defined or imported
rnouw0xu.21w(4,127): error CS0518: Predefined type 'System.String' is not defined or imported
rnouw0xu.21w(8,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
rnouw0xu.21w(9,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
rnouw0xu.21w(10,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
rnouw0xu.21w(11,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
rnouw0xu.21w(13,36): error CS0234: The type or namespace name 'Rendering' does not exist in the namespace 'Microsoft.AspNetCore.Mvc' (are you missing an assembly reference?)
rnouw0xu.21w(14,36): error CS0234: The type or namespace name 'ViewFeatures' does not exist in the namespace 'Microsoft.AspNetCore.Mvc' (are you missing an assembly reference?)
rnouw0xu.21w(29,35): error CS0234: The type or namespace name 'Razor' does not exist in the namespace 'Microsoft.AspNetCore' (are you missing an assembly reference?)
rnouw0xu.21w(29,78): error CS0518: Predefined type 'System.String' is not defined or imported
rnouw0xu.21w(29,87): error CS0518: Predefined type 'System.String' is not defined or imported
I trided to fix this erros in many different ways bul it looks like I got stuck here.
Looks like i found answer in this article:
https://github.com/aspnet/Razor/issues/1212
I just added this code to my test.csproj file:
<Target Name="CopyDepsFiles" AfterTargets="Build" Condition="'$(TargetFramework)'!=''">
<ItemGroup>
<DepsFilePaths Include="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />
</ItemGroup>
<Copy SourceFiles="%(DepsFilePaths.FullPath)" DestinationFolder="$(OutputPath)" Condition="Exists('%(DepsFilePaths.FullPath)')" />
</Target>
Just extending the approved answer a bit since the suggested fix didn't work for me when upgrading to .NET 6, runtime was still unable to locate the assemblies until I explicitly added a AddApplicationPart(assembly) call to the IMvcBuilder.
Also a minor simplification is to pass the options lambda to the AddRazordRuntimeCompilation call, in which case services.Configure<MvcRazorRuntimeCompilationOptions> can be removed.
It might have failed due to several reasons (this was a Windows service project, views were in a separate dll), but anyway this is a compilation of various fixes I gathered from the web:
// this part is needed if you don't have a valid IWebHostEnvironment
// service registered, in which case you need to create your own dummy
// implementation because Razor needs IWebHostEnvironment.ApplicationName
// (it should return Assembly.GetEntryAssembly().GetName().Name, and you
// can leave other properties null)
services.AddSingleton<IWebHostEnvironment, DummyHostingEnvironment>();
services.AddSingleton<IHostEnvironment, DummyHostingEnvironment>();
// this also needs to be registered as two separate dependencies
// if you're getting "Unable to resolve service for type
// 'System.Diagnostics.DiagnosticListener'"
// (see https://github.com/dotnet/aspnetcore/issues/14544)
var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticSource>(diagnosticSource);
services.AddSingleton<DiagnosticListener>(diagnosticSource);
// make sure you specify correct assemblies, in case the views
// are in a separate dll
var assemblyWithTemplates = ...;
var assemblyReferencingTheRazorPackage = ...;
services
.AddRazorPages()
.AddApplicationPart(assemblyReferencingTheRazorPackage ) // <-- added this
.AddRazorRuntimeCompilation(options =>
{
// important to clear because some of them are null
options.FileProviders.Clear();
// resolve views as embedded resources
options.FileProviders.Add(new EmbeddedFileProvider(assemblyWithTemplates));
});
And then also add the code from the accepted answer to the .csproj file so that .deps files are properly copied.
I want to send email using SendGrid using Azure function. I am using c# code to do it. Below is my sample code. When I compile the code, I am getting below error,
#r "System.Configuration"
#r "System.Data"
#r "SendGrid"
using System;
using System.Net;
using System.Configuration;
using SendGrid;
using SendGrid.Helpers.Mail;
public static async Task < HttpResponseMessage > Run(HttpRequestMessage req, TraceWriter log) {
var client = new SendGridClient(sendgridApiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("sample#gmail.com", "DX Team"),
Subject = "Hello World from the SendGrid CSharp SDK!",
PlainTextContent = "Hello, Email!",
HtmlContent = "<strong>Hello, Email using HTML!</strong>"
};
var recipients = new List<EmailAddress>
{
new EmailAddress("test#gmail.com", "John"),
new EmailAddress("sa#gmail.com", "Sam")
};
msg.AddTo(recipients);
msg.SetFooterSetting(
true,
"Some Footer HTML",
"<strong>Some Footer Text</strong>");
var response = await client.SendEmailAsync(msg);
}
Error:-
The type or namespace name 'SendGridClient' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'SendGridMessage' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'EmailAddress' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'EmailAddress' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'EmailAddress' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'EmailAddress' could not be found (are you missing a using directive or an assembly reference?)
Compilation failed.
My references is here
How do I solve this?
According to your description, I checked this issue, you could refer to the following steps to install SendGrid package via azure portal as follows:
Note: Since you have multiple recipients, you need to use msg.AddTos(recipients).
Additionally, as J. Steen commented that you could refer to How can I use NuGet packages in my Azure Functions?
for more details. Moreover, you could refer to here for more details about how to deploy pre-compiled assemblies to azure functions.
You are missing the NuGet package reference. To add it, create a project.json file of the following content:
{
"frameworks": {
"net46":{
"dependencies": {
"Sendgrid": "9.5.0"
}
}
}
}
As a side note, I recommend you trying to use SendGrid output binding instead of sending the mail with custom code. You'll basically have and output parameter of type Mail, and the rest will be done by the binding.
For runtime version 3, I have created a function.proj file like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SendGrid" Version="9.12.6" />
</ItemGroup>
</Project>
You can create this file using an editor and click View Files o(on the right side) -> Upload in the portal to upload it to your function.
And simply at the top of the function:
using SendGrid;
using SendGrid.Helpers.Mail;
solved my similar problem.
I have deleted
#r "System.Configuration"
#r "System.Data"
at the top.
i was working on a console application and the word "From" wasn't a problem
ex var Best = db.Select<TopSellingGraph>(
db.From<products>
.Join<SalesOrderDetail>());
but when i start to use the servicestack api i always go into this problem
the error message is Error 1 'System.Data.IDbConnection' does not contain a definition for 'From' and no extension method 'From' accepting a first argument of type 'System.Data.IDbConnection' could be found (are you missing a using directive or an assembly reference?)
and i put in the apphost this code
var conString = ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
var conFactory = new OrmLiteConnectionFactory(conString, SqlServerDialect.Provider, true);
container.Register<IDbConnectionFactory>(c => conFactory);
i did exactly like the git-hub course
https://github.com/ServiceStack/ServiceStack.OrmLite
anyone have any idea ?
Most of OrmLite's APIs are extension methods over ADO.NET's IDbConnection interfaces which are made available when using the ServiceStack.OrmLite namespace:
using ServiceStack.OrmLite;
Tools like ReSharper help identify, add and can alleviate the burden of dealing with namespaces in C#.