ASP.NET Core 6 MVC : adding identity failing - asp.net-core-mvc

I'm using VS 2022, ASP.NET Core 6 MVC and Microsoft SQL Server 2019 (v15).
Git project: [https://github.com/Wizmi24/MVC_BookStore]
I'm trying to add --> new scaffolded item --> identity.
Default layout page, override all files and mine Data context
when I click add, I get this error:
There was an error running the selected code generator:
'Package restore failed. Rolling back package changes for 'MyProjectName'
I cleared NuGet Package cache as I saw it may help, but all it do is just prolong and this same error is visible after trying to install Microsoft.EntityFrameworkCore.SqlServer, which is installed. I checked the packages and made sure they are the same version (6.0.11).

I cloned your project to test, and the problem you mentioned did appear. Not sure why, but I finally got it working by updating the NuGet package:
I updated the two packages Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.Relational to version 7.0.1 (you need to pay attention to the sequence when updating), then add scaffolded Identity, and I succeeded.
You can try my method, if the Identity is successfully added, but the following exception is encountered at runtime:
You need to add builder.Services.AddDbContext<MyBookContext>(); before
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<MyBookContext>();
MyBookContext is the Data context class selected when you add Identity:
In addition, if there is a 404 error in your area routing, you can refer to this document to modify it.
Hope this can help you.
Edit1:
I think it might be a problem caused by naming duplication. Please try to change the name of the context generated by Identity.
As you can see, the ApplicationDbContext generated by Identity is consistent with the ApplicationDbContext namespace in your MyBook.DataAccess:
So naming the same will cause conflict:
So you need to change the naming to avoid conflicts. For example:
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
));
builder.Services.AddDbContext<ApplicationDbContextIdentity>();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContextIdentity>();
Edit2:
As I mentioned in the original answer, if you get a 404 error, you can try to refer to this link to fix the area routing.
The easiest way is to directly change the routing settings in Program.cs:
app.MapAreaControllerRoute(
name: "Customer",
areaName: "Customer",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
Then add the Area property to the controller:
[Area("Customer")]
public class HomeController : Controller{}
There seems to be a problem with your Repository.cs, so I changed the Index to only output a string to test the result.
public string Index()
{
return "success";
}
Test Result:
If your Repository.cs also has problems when you test it, you can make a new post for everyone to help you fix this problem(Because this question strays so far from your original question, one post is better off addressing only one question).
Good Luck.

Related

Error trying to scaffold a view in ASP.NET Core 6.0 MVC

I'm trying to scaffold a new razor view using Visual Studio. I select a template, my model and my DbContext, then I get the error message shown below.
Things to note. My models, my DbContext and my website are all in different projects. From the message below I am using AddDbContext and I have a constructor that accepts a DbContextOptions<TContext> parameter.
I read a comment on a blog post that the issue is because my context is in another project. The comment referenced something about the need to inject the Configuration into the DbContext to get the connection string and manually add it in the OnConfiguring override.
I can't find any examples if this is correct or how to set it up. Any help would be appreciated.
EDIT:
Testing out the theory from the blog comment I mentioned above, I added this section into my DbContext. ConnectionString is a hardcoded string constant with my connection information. This does work and allow me to scaffold, so the question still remains. How can I inject this connection string into my DbContext to allow the scaffolding to work?
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
else
{
base.OnConfiguring(optionsBuilder);
}
}
EDIT: So after making this change, I checked in the code and had another developer pick it up. It appears this section above just needs to be there to allow scaffolding to work. He never changed the connection string to point to his environment. He no longer got the error above it just worked.
I am not sure about what is the actual problem but it seems like we were having problems creating DbContext at design time. I manually added the code below and it's working now. It's just a temporary solution tho.
public AppDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=JwtTemplate;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
return new AppDbContext(optionsBuilder.Options);
}
Reference: https://stackoverflow.com/a/70559350

Elsa workflow versioning

I have created a simple workflow, first time publish it is working fine when I change something and publish then it is throwing an exception: "The call is ambiguous and matches multiple workflows". How to handle this?
I was experiencing the same issue. There appears to be an issue in Elsa where the "IsLatest" flag on the WorkflowDefinition table doesn't get turned off for the prior version of that workflow. There is some documentation around the issue here:
https://gitmemory.com/issue/elsa-workflows/elsa-core/1293/886656398
In my case, I fixed this by manually setting the prior version's IsLatest to 0 and restarting Elsa. The restart was important, as there appears to be some caching related to the workflow newness.
TL;DR : there are multiple workflows with the same path
Check if you are building a workflow through ELSA DESIGNER and at the same time there is a workflow that is triggered when HTTP requests are made to the same URL
public class HelloWorld : IWorkflow
{
public void Build(IWorkflowBuilder builder)
{
builder
.HttpEndpoint("/hello") // this is the endpoint that is causing conflict
.When(OutcomeNames.Done)
.WriteHttpResponse(HttpStatusCode.OK, "<h1>Hello World!</h1>", "text/html");
}
}

Xamarin.Auth - Google authentication won't open in browser

I'm trying to do authentication on my Android application using Xamarin.Auth. Some time ago, Google made the policy that you cannot do this in an embedded web view (for totally valid reasons).
I'm trying to open the account authentication page in a browser, but keep getting the embedded web view. I understand that isUsingNativeUI needs to be true in the following code:
_auth = new OAuth2Authenticator(clientId, string.Empty, scope,
new Uri(Constant.AuthorizeUrl),
new Uri(redirectUrl),
new Uri(Constant.AccessTokenUrl),
null,
isUsingNativeUI = true);
At every point in my application, this always equals true.
Elsewhere, I have code that redirects to what should be a browser:
var authenticator = Auth.GetAuthenticator();
Intent intent = authenticator.GetUI(this);
this.StartActivity(intent);
Regardless, I keep getting a dreaded 403 disallowed_useragent error whenever I try to run the project. Is there another element to this that I'm missing?
To my knowledge, setting auth.IsUsingNativeUI = true in the constructor should dictate that it must open in a browser. I've been following this example to try and debug with no success. I even pulled the guy's repo down to my machine and ran it - the Intent variable at the moment of redirection is almost identical.
Could there be something stupid that I'm missing? What else might be going wrong?
I realize this is an old question, but I had the same issue.
You have to install version 1.5.0.3 of the Xamarin.Auth Nuget package. The newest one (version 1.7.0 right now) doesn't work. You'll have to also install the PCLCrypto nuget package in order to get that version to work.

Registering a Sitefinity Custom Membership provider

I am trying to implement a custom membership provider in Sitefinity, and have followed through the documentation at: http://docs.sitefinity.com/tutorial-create-a-custom-membership-provider
When I come to register the provider in the Sitefinity backend, I get the message The following required properties are not set: type
I have checked, double checked and checked again the namespace and class names, and can even declare a variable as the provider type in the code-behind, yet it just won't have it.
My provider is defined thus:
namespace SitefinityWebApp
{
public class WebsiteMembersProvider : MembershipDataProvider
{
public WebsiteMembersProvider()
{
//... etc
I am registering the provider in the SF backend as:
SitefinityWebApp.WebsiteMembersProvider, SitefinityWebApp
And I can go into the code behind on one of my master pages and code:
SitefinityWebApp.WebsiteMembersProvider MyTestProvider;
and indeed, the class appears in the intellisense offerings just fine.
and the project all compiles/runs fine - but SF won't let me use the custom provider! I have also tried adding the provider manually in the securityconfig.config file - similar result.
Any idea anyone?
I went through the tutorial to try it myself and ran into the same problem as you.
Are you sure that you're putting this
SitefinityWebApp.WebsiteMembersProvider, SitefinityWebApp
in the ProviderType field (and not the 'Global resource class ID' field, which is what I initially did)? It seems like that error message shows up if I remove the text from that field and attempt to save (and also when it can't resolve that type).
Otherwise, I'm not sure what else it could be, aside from maybe recycling the app pool.

Ninject + MVC3 = InvalidOperationException: Sequence contains no elements

I created a new MVC3 project, hit F5, saw the sample page.
Then I used NuGet to get the Ninject.MVC extension. I modified my global.asax according to the Ninject documentation, How To Setup an MVC3 Application:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional });
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Now when I run the app, I get the yellow screen of death with the following exception:
InvalidOperationException - Sequence contains no elements.
at System.Linq.Enumerable.Single(...)
at Ninject.Web.Mvc.Bootstrapper.Initialize(...)
line 67.
And sure enough, line 67 of that file calls .Single(), thus throwing the exception.
What am I doing wrong?
I have to add to this in the hopes that someone else will resolve the issue more quickly and not want to pull out every strand of hair on their head like I almost did.
I needed to rename everything in my project to match new business terms. I changed namespaces everywhere and I even changed the Assembly Name (right-click project > properties > application tab) so that the generated assembly matches the new naming convention. The assembly rename is what made Ninject very angry!
By renaming the assembly that gets generated a new file with the new name was being created when we compiled. However, the old file with the old name was still in the bin directory! If you have Ninject activating via the added class in App_Start then this activation class will get invoked in BOTH assemblies (old one AND new renamed one). Don't ask me how or why, but it does and it gives you this "already initialized" error.
Not even cleaning solution works because Visual Studio will only remove the binaries that it is generating, which would be the new renamed ones. It leaves the old ones alone just sitting there.
Go delete your bin folder before you try doing anything else! I hope this saves someone else from wasting valuable working hours!
You might notice that after installing the ninject.mvc3 NuGet there is an App_Start subfolder created inside your project containing an NinjectMVC3.cs file. Delete this folder and try again. So here are the steps I followed:
Create a new ASP.NET MVC 3 project using the default template
Bring up the Package Manager Console window (View -> Other Windows -> Package Manager Console)
Type install-package ninject.mvc3 on the command line
Replace the default code in Global.asax with the code in your question
Delete the AppStart subfolder created during the installation of the package
Run the application
Enjoy the beauty of the /Home/Index default page opened in your Google Chrome web browser :-)
I have updated the documentation Wiki linked in your question to show both ways to setup a MVC3 application. I suggest to use the second option which is the prefered way for theNuGetpackage.
Instead of deriving from NinjectHttpApplication it is using the NinjectMVC.cs in the AppStart folder which is created during installation of the package. This is also the location where you create the kernel and where you load your modules or where you define the bindings.
As Alex Ford said:
I have to add to this in the hopes that someone else will resolve the
issue more quickly and not want to pull out every strand of hair on
their head like I almost did.
I had a special version of that problem which could get solved as follows:
Exception Details: System.InvalidOperationException: Sequence contains no elements
This error is caused by the fact that there are 2 projects with
App_Start/NinjectWebCommon.cs
Removing the file eliminates the error.
Note: if you are nu-getting Ninject.Web.Common because you need to
reference Ninject.Web.Common assembly for one of your class library
project, you can safely remove the “App_Start” folder and
“NinjectWebCommon.cs”. It is meant for web/web api projects.
>click here to view the original blog entry<
My solution was that I had set the App_Start folder property, Namespace Provider to True.
I had changed this to False so that Resharper wouldn't highlight the namespace NOT matching the folder structure.
Wanted to add one more cause ...
We installed the Ninject.MVC3 package to multiple projects - only one of which was an actual MVC applicaiton. However, we forgot to remove the App_Start folder.
Removing the App_Start folder from the referenced project resolved the issue.
To tack on to #Chev's answer... this was my ultimate issue as well. If you're deploying to an Azure Website (now named AppSite), you want to click on this box in the publish to remove old files

Resources