ASP.NET Identity Is default ApplicationUserManager implementing IUserEmailStore? - c#

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

Related

The call is ambiguous between the following methods or properties during migration from Net Core 3.1 to Net 6

I am trying to migrate from .Net Core 3.1 to .Net 6. I updated TargetFramework and some dependencies.
And I have this piece of code
public CustomerSettingsDefaults(Microsoft.Extensions.Configuration.IConfigurationSection configuration)
{
....
var personalizedUrls = configuration.GetRequiredSection(#"PersonalizedUrls");
However during project build it
Severity Code Description Project File Line Suppression State
Error CS0121 The call is ambiguous between the following methods or
properties:
'Microsoft.Extensions.Configuration.ConfigurationExtensions.GetRequiredSection(Microsoft.Extensions.Configuration.IConfiguration,
string)' and
'Common.Extensions.ConfigurationExtensions.GetRequiredSection(Microsoft.Extensions.Configuration.IConfiguration,
string)' Crm.Infrastructure C:...\Configuration\CustomerSettingsDefaults.cs 23 Active
My ConfigurationExtensions is defined like this
namespace Common.Extensions
{
public static class ConfigurationExtensions
{
public static IConfigurationSection GetRequiredSection(this IConfiguration configuration, string sectionName)
{
var section = configuration.GetSection(sectionName);
if (section is null)
{
throw new InvalidOperationException($#"The configuration is missing the {sectionName} section");
}
return section;
}
}
}
How to fix it?
Well, there's a conflict between your own GetRequiredSection extension method and the GetRequiredSection that was added to Microsoft.Extensions.Configuration.Abstractions in .NET 6. Both extend the same interface and take the same parameters, so if both namespaces (your Common.Extensions and .NET's Microsoft.Extensions.Configuration) are in scope, of course the compiler doesn't know which one to pick.
So you could just delete your own extension method altogether, since it seems to do the same thing that the one provided by .NET does, and that means one less thing to maintain for you.
If you absolutely need to keep using your own method, then you need to call it explicitly like a static method:
var personalizedUrls = Common.Extensions.ConfigurationExtensions.GetRequiredSection(configuration, "PersonalizedUrls");
'Call is ambiguous' error is always for those function calls for which there are 2 similar function in the code in which neither functions are either overloading or overriding the other function.
To get rid of the error and you want to call a specific function, either you can call out the whole function i.e.,
instead of calling
GetRequiredSection(), call
Common.Extensions.ConfigurationExtensions.GetRequiredSection()

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

Task does not contain a definition for 'FirstOrDefault'

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.

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

Missing extension methods in HtmlHelper using NHaml

I discovered NHaml some days ago and it's a great project.
When I try to use MVC2 Html helpers like Html.LabelFor(), Html.TextBoxFor(); the views won't compile.
Example:
error CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'LabelFor' and no extension method 'LabelFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
0185: textWriter.Write(" ");
0185: textWriter.Write(Convert.ToString(Html.LabelFor(model => model.Username)));
0187: textWriter.WriteLine();
error CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
0194: textWriter.Write(" ");
0194: textWriter.Write(Convert.ToString(Html.TextBoxFor(model => model.Username)));
0196: textWriter.WriteLine();
I tried to add assemblies and namespaces in the nhaml's Web.config section but it doesn't change anything.
I'm using :
System.Web.Mvc 2.0
.NET Framework 3.5 SP1
Nhaml 1.5.0.2 from git trunk (and tried other builds)
My NHaml configuration is:
<nhaml autoRecompile="true" templateCompiler="CSharp3" encodeHtml="false" useTabs="false" indentSize="2">
It looks like you have an assembly reference problem.
You are probably referencing the MVC 1.0 assemblies, instead of 2.0 assemblies?
The problem is the view class contains a non-generic HtmlHelper. Or some new extension methods requires the ViewData.Model's type.
To correct this problem, change the property and instantiation in NHaml.Web.Mvc/NHamlMvcView.cs.
//public HtmlHelper Html { get; protected set; } // line 42
public HtmlHelper<TModel> Html { get; protected set; }
//Html = new HtmlHelper( viewContext, this ); // line 37
Html = new HtmlHelper<TModel>( viewContext, this );
Rebuild and use :)
As far as I can see the new MVC helpers are not supported, actually only a limited amount of HtmlHelpers are namely LinkExtensions. As a wild guess, you can possibly try to adding the LabelExtensions to the setup of the NHaml viewengine in the NHaml.Web.Mvc/NHamlMvcViewEngine.cs file (since you do have the source) and check if that works.
private void InitializeTemplateEngine()
{
// snip
_templateEngine.Options.AddReference( typeof( LabelExtensions ).Assembly.Location ); // Line 50
}

Categories