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
Related
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.
I'm currently trying to load embedded ViewComponents from external assemblies.
I've included this in my project file:
<EmbeddedResource Include="Views\**\*.cshtml" />
so when I inspect the actual assembly and run GetManifestResourceNames() I see that the file is embedded.
I'm then calling this method in ConfigureService() in Startup.cs:
public static IMvcBuilder GetModules(this IMvcBuilder mvcBuilder)
{
var embeddedFileProviders = new List<EmbeddedFileProvider>
{
new EmbeddedFileProvider(Assembly.GetCallingAssembly())
};
mvcBuilder.ConfigureApplicationPartManager(apm =>
{
foreach (string modulePath in Directory.GetFiles(Configuration.Settings.Path, "*.Module.dll"))
{
var assembly = Assembly.LoadFrom(modulePath);
var startUpType = (from t in assembly.GetTypes()
where t.GetInterfaces().Contains(typeof(IModuleStartup))
select t).FirstOrDefault();
RegisterModuleServices(mvcBuilder, startUpType);
apm.ApplicationParts.Add(new AssemblyPart(assembly));
embeddedFileProviders.Add(new EmbeddedFileProvider(assembly));
Modules.Assemblies.Add(assembly);
}
var compositeFileProvider = new CompositeFileProvider(embeddedFileProviders);
mvcBuilder.Services.AddSingleton<IFileProvider>(compositeFileProvider);
});
return mvcBuilder;
}
I'm also not using
mvcBuilder.Services.Configure<RazorViewEngineOptions>(o =>
{
o.FileProviders.Add(compositeFileProvider);
});
as this doesn't work at all and the action o.FileProviders.Add(compositeFileProvider) is not even called.
All the embedded file providers are found when I inject IFileProvider but none of the files are found when I run _fileProvider.GetDirectoryContents("");
Does anybody have any idea why?
So i figured out why it wasn't returning anything...
It seems that I didn't set the baseNameSpace parameter when created the new EmbeddedFileProvider. stupid huh.
But there were quite a few examples that didn't set this and it worked.
Hopefully this helps some other people out there if they experience this issue.
Watch also your project root namespace setting. My case was the reverse - I copy-n-pasted a project file and it did not retain the namespace setting from the previous project. This was because I did not explicitly set <RootNamespace>YourNameSpaceNameHere</RootNamespace> in the .csproj settings
(nested under the <PropertyGroup> block at the top), so it took my file name as the namespace! It was quite a "gotcha" moment, and much time lost, to find out my code correctly sets the baseNameSpace parameter, but the whole time the project was storing the files under a different namespace! (you can open the DLL in any text editor, scroll to the bottom, and you should easily be able to make out the embedded text to verify). It was there, just not found. In case someone has this correct, you can also dump ALL files using {Assembly}.GetManifestResourceNames() and make sure your names are correct.
In my case I had '.' (period) in the resource filename.
I had this error in an ASPNET Core 3.0 project, where my external class library had the file correctly embedded, but the web application was not locating them at runtime. It turns out the example I copied from the internet had a namespace provided and I copied that example namespace without considering the implications...
After a bit of research, I was able to fix it by simply using the proper root namespace defined my own Class Library:
var embeddedFileProvider =
new Microsoft.Extensions.FileProviders
.EmbeddedFileProvider(assembly, "ViewComponentLibrary");
changed to
var embeddedFileProvider =
new Microsoft.Extensions.FileProviders
.EmbeddedFileProvider(assembly, "MyProjectLibrary");
We had another root cause leading to this problem. We had migrate our build agents from windows to linux, and FS case-sensitivity of the latter did the trick - it didn't found embedded resources:
<EmbeddedResource Include="swagger\ui\*" />
because on file system we have Swagger\ui\
So the #(EmbeddedResource) path must be the same as the File System path:
<EmbeddedResource Include="Swagger\ui\*" />
(or rename files/directories, to match the #(EmbeddedResource).
Here's the scenario.
I created a brand new Asp.Net DNX RC2 Final project. I also added a .Net class library project to my solution (both under FX 4.6.1). The class library project is located in the src folder.
Then, I add a reference to the class library, and it can successfully restore all packages after making changes to the project.json file.
I've added a simple foo function to my class library
namespace ClassLibrary1
{
public class Class1
{
public static string Foo()
{
return "Bar";
}
}
}
and finally in my Home/Index view, I have added the following on top
<div>
#(ClassLibrary1.Class1.Foo())
</div>
The solution compiles with no errors.
You may think so far so good, let's continue.
Then, when I run the solution, the following is shows:
At runtime, my class library is not available.
I ran into a similar situation. In my case I got a RazorEngine exception in Visual Studio which at least gave me an indication of what was going on (it was something like a missing reference exception, even though the class library was added as a reference).
The only way that I could get it working (I'm hoping there is a better way), was to add the following code to my ConfigureServices method in Startup.cs:
services.Configure<RazorViewEngineOptions>(options =>
{
var previous = options.CompilationCallback;
options.CompilationCallback = (context) =>
{
previous?.Invoke(context);
context.Compilation = context.Compilation.AddReferences(MetadataReference.CreateFromFile(typeof(ClassLibrary1.Class1).Assembly.Location));
};
});
I got the idea from the following websites:
Callback on RazorViewEngineOptions
Configure RazorViewEngine
I did confirm that your example is working when I add the code mentioned above.
I have a ASP.NET 5 , MVC 6 project which has reference to a CL in the same solution.
When I try to debug I am unable to enter to the CL's breakpoints.
When I come to the function calling the CL and hit F11 it just continues , so it doesn't enter into the function for debug.
When I debug and get over to the function of the CL and choose "Step into specific" and choose the function it says :
Microsoft.AspNet.Mvc.Core.pdb not loaded.
Microsoft.AspNet.Mvc.Core.pdb contains the debug information required to find the source for the module Microsoft.AspNet.Mvc.Core.dll
Module Information
Version : 6.00.0.10417
Original Location : <path in local disk>
Try one of the following options :
Change existing PDB and binary search paths and retry:
Microsoft Symbbol Servers
So when I try to get it load from microsoft symbol server it says :
Microsoft.AspNet.Mvc.Core.pdb could not be found in the selected paths
My main project is in MVC 6 and my dll is target framework : .Net 4.5.2
I think that due to the beta nature the pdb files are not on the symbol servers. I would assume that after RTM (remember VS is RC but asp.net 5 is very much still beta) they would be added to the symbol servers.
If you need support before that you can clone the asp.net MVC repository (https://github.com/aspnet/Mvc.git) to a location outside your project. Then in the global.json (solution level file) add that path to the project property. This will instruct the compiler to look there for dependency resolution. The compiler will always attempt to resolve dependency using local source over nuget package. In Visual Studio right click on references > restore packages. You should see the package icon change to indicate source. Then you can simply build, and step directly into the source.
This error can be occurred because of a wrong doing in code. I got this error once where I was implementing a base class and overriding its method without a base method call where my db context was initialized. But in my controller I was trying to use the db context which is still not initialized which caused a null reference error. Once I fixed it this error disappeared.
public class MyController : BaseController
{
private MyService _myService;
protected override void Initialize(RequestContext requestContext)
{
//I missed the base call here
//base.Initialize(requestContext);
_myService = new MyService(myDbContext);
}
}
public class BaseController : Controller
{
public MyDbContext myDbContext { get; set; }
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
myDbContext = HttpContext.GetOwinContext().Get<MongoDbContext>();
}
}
Try deleting the bin folder and rebuilding the solution.
I got a problem migrating from VS.Net 2008 / MVC 1 to VS.NET 2010 (+C# 4.0) / MVC 2
The web.config has been updated, the site runs well in Cassini, but my problem now is deploying on IIS 6.
I updated the web site to run using ASP.Net 4,
but whatever URL I try, I always have a 404 error. It's as if the routing was not taken into account (yes, the wildcard mapping has been done).
I do not understand this mess and could not google anything interesting...
Thanks for your suggestions !
Ok I got y answer (thanks to a colleague)
When migrating from ASP.Net 2.0 to ASP.Net4.0,
if you meet the same problem,
then check in Web Service Extension if ASP.Net v4 is Allowed.
In my case, after installing the .Net framework 4, it was prohibited.
Will & Mark : thanks for your help, hope it will helps others.
I think I know what's happening: on IIS6, as well as the wildcard mapping you will need a default document (Default.aspx) that routes folder requests to the MVC handler.
There was one included with the MVC1 project templates, but it has been removed in MVC2.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YourNameSpace._Default" %>
<%-- Please do not delete this file. It is used to ensure that ASP.NET MVC is activated by IIS when a user makes a "/" request to the server. --%>
and Default.aspx.cs:
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace YourNameSpace
{
public partial class _Default : Page
{
public void Page_Load(object sender, System.EventArgs e)
{
// Change the current path so that the Routing handler can correctly interpret
// the request, then restore the original path so that the OutputCache module
// can correctly process the response (if caching is enabled).
string originalPath = Request.Path;
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
HttpContext.Current.RewritePath(originalPath, false);
}
}
}
When you say "It's as if the routing was not taken into account", I suspect that it actually isn't, and this is your problem.
This finally fixed it for me:
I commented earlier, and a wee bit prematurely. My comment to Mark B's post was getting my initial Index view to show up, but then I kept getting the 404 errors whenever I navigated to any other view.
I was also distracted by the green check mark approved solution in this particular forum, but I could not even see the web server extensions folder in IIS 6 on my desktop; therefore, I had no control from that stand point of enabling aspnet 4.0, though I made sure it was installed by performing running the following command line:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i
Now for the actual piece that finally allowed me to navigate to the other views besides just my Home/Index:
In the Global.asax.cs file of your VS 2010 Solution, you will see code as follows in the RegisterRoutes method:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
I simply added ".aspx" after the {action} section of the tag as follows:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}.aspx/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
And ahla wahla Peanut Butter and Jelly sandwiches. :0)
If you want to do it in C#, just add the System.DirectoryServices reference and this piece should do the job nicely.
DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/W3SVC");
w3svc.Invoke("EnableWebServiceExtension", "ASP.NET v4.0.30319");
w3svc.CommitChanges();
HTH