Task does not contain a definition for 'FirstOrDefault' - c#

Error CS1061 'Task>' does not contain a definition for
'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a
first argument of type 'Task>' could be found (are you
missing a using directive or an assembly reference?) ,
making a web application with facebook controller, included using system.linq but still getting the error for FirstOrDefault().
I dont know what the problem is, i reinstalled visual studio too as he same thing works for my friends laptop.
I juggled around to see if the method is present in the library and it is there but still not getting past this Image for the same
public async Task<ActionResult> Posts()
{
var currentClaims = UserManager.GetClaimsAsync(HttpContext.Identity.GetUserId());
// Error occurs here at FirstOrDefault
var accesstoken = currentClaims.FirstOrDefault(x = > x.Type == "urn:tokens:facebook");
if (accesstoken == null)
...
}

You are missing an await in front of UserManager.GetClaimsAsync():
var currentClaims = await UserManager.GetClaimsAsync(...);

Look closely at the error message. GetClaimsAsync returns type Task<IList<Claim>>, not type list. The Task type doesn't have a FirstOrDefault method. As other people have indicated, await GetClaimsAsync and it'll work.
As a side note, do not use .Result here as that will deadlock in most environments. See this article for an explanation of why this will deadlock as well as this article on async/await best practices.

Related

Getting error on AuthenticationParameters and AcquireToken

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

'IApplicationBuilder' does not contain a definition for 'HttpContext'

I am trying to configure the handling of certain HTTP Response Status Codes in the middleware of my ASP.NET Core 2.2 MVC app using this example code from Microsoft docs:
app.UseStatusCodePages(async context =>
{
context.HttpContext.Response.ContentType = "text/plain";
await context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
But it displays an error for HttpContext saying
'IApplicationBuilder' does not contain a definition for 'HttpContext'
and no accessible extension method 'HttpContext' accepting a first
argument of type 'IApplicationBuilder' could be found (are you missing
a using directive or an assembly reference?)
I see that context is of type Microsoft.AspNetCore.Diagnostics.StatusCodeContext which has a HttpContext property. Why is it not recognizing HttpContext?
P.S. I tried installing these NuGet packages to no avail:
Microsoft.AspNetCore.Diagnostics
Microsoft.AspNetCore.Diagnostics.Abstractions
Microsoft.AspNetCore.Http
Microsoft.AspNetCore.Http.Abstractions
Microsoft.AspNetCore.Http.Extensions
Microsoft.AspNetCore.Http.Features
Discovered the issue ... it's a bit odd: When I check Intellisense on the first instance of HttpContext it doesn't offer any suggestions for using statements, but when I do it on any of the other instances it suggests adding a reference to Microsoft.AspNetCore.Http, which fixes it.
I'm not sure why it's not finding that suggesting when I check the first HttpContext.
You need to return a Task from your lambda expression for the compiler to recognize the correct overload.
You are trying to use this overload:
UseStatusCodePages(IApplicationBuilder, Func<StatusCodeContext,Task>)
But since your lambda expression doesn't return a Task, the compiler is using this overload:
UseStatusCodePages(IApplicationBuilder, Action<IApplicationBuilder>)
Consequently, your context variable is actually referring to an instance of IApplicationBuilder, not StatusCodeContext.
Returning the Task from WriteAsync should do the trick:
app.UseStatusCodePages(context =>
{
context.HttpContext.Response.ContentType = "text/plain";
return context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
You are missing some using statements. Sometimes IntelliSense doesn't quite pick up on where you want to go (statement is probably ambiguous). You could be more specific and code it like this:
async (StatusCodeContext ctx) => ...
Which, in your case would most likely let IntelliSense suggest some using statements that you need, after which you can replace with:
async ctx => ...
again, and it should probably work.

XUnit HttpStatusCode does not contain a definition for Should

I am writing XUnit test case. I am getting following error
Error CS1061 'HttpStatusCode' does not contain a definition for 'Should' and no accessible extension method 'Should' accepting a first argument of type 'HttpStatusCode' could be found (are you missing a using directive or an assembly reference?)
What does the error say and how to solve it. Please any one try to help me.
Thank you..
For Should, there is no built-in Should to achieve the similiar function Assert.Equal(HttpStatusCode.OK, defaultPage.StatusCode);.
You could try shouldly to simplify the Assert.Equal.
Install-Package Shouldly
Referer by using Shouldly;
Useage
public async Task Test()
{
var server = new TestServer(WebHost.CreateDefaultBuilder()
.UseStartup<TestStartup>()
);
var response = await server.CreateClient().GetAsync(#"/test");
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
var result = await response.Content.ReadAsStringAsync();
}

ASP.NET Identity Is default ApplicationUserManager implementing IUserEmailStore?

Hello,
I was looking into ASP.NET Identity source, particulary, in UserValidator. I wanted to rewrite it for my own project, to be able to change error messages. So I copy that class into my project. When I try to use it - I get an error - 'Microsoft.AspNet.Identity.UserManager<TUser,TKey>' does not contain a definition for 'GetEmailStore' and no extension method 'GetEmailStore' accepting a first argument of type 'Microsoft.AspNet.Identity.UserManager<TUser,TKey>' could be found (are you missing a using directive or an assembly reference?)
at this line
var email = await Manager.GetEmailStore().GetEmailAsync(user).ConfigureAwait(false);
My question is - how can this work in AspNet.Identity framework, but not in my project? It doesn't look like that Manager is implementing IUserEmailStore.
All I tested, was default MVC template in VS2013
I finally found the answer (after searching a lot).
If you see the UserManager's source code, the GetEmailStore() method does exist, but is internal. Take a look:
internal IUserEmailStore<TUser, TKey> GetEmailStore()
{
var cast = Store as IUserEmailStore<TUser, TKey>;
if (cast == null)
{
throw new NotSupportedException(Resources.StoreNotIUserEmailStore);
}
return cast;
}
So, it exists only inside files of the own Identity assembly, that's why it works there and not in your code.
Moreover, you can achieve the same result as follow:
var email = await Manager.GetEmailAsync(user.Id).ConfigureAwait(false);
Click here to see UserManager's Source Code

ServiceStack Ormlite System.Data.IDbConnection' does not contain a definition for 'From'

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#.

Categories