Fail at controller creation - asp.net-mvc

Using EF 6.1.1
(Reinstalled VS2013 + Update) x4
Happen at each web application project
Transcript:
Error
There was an error running the selected code generator:
'Object reference not set to an instance of an object.'
Just looked up everywhere on the internet, and nothing works, like:
Restarting VS
Reinstalling VS
Executing Install-Package MvcScaffolding
Creating another project
Checking database if exists
Searching the internet
Crying
Now, posting on SO
I'm running out of idea for how to resolve that Helpless error
NB1: My database is created using an *.edmx file and SSMS
Thanks for future answers/hints

What DB do you use? I was having similar problems with MySQL, but I was using additional extensions for that DB. (Solved that by reinstalling several times the extension and saving the .edmx every time in source control while working so when it crash can revert it back :) )
Please check the answer of similar question (hope that helps): Scaffolding controller doesn't work with visual studio 2013 update 3 and 4
After having so much issues with .edmx - do not use them... I know is much more code writing but then you can more easily control and modify it when the db design has changed.

Related

Can't Add View from Controller in VS 2015 : "There was an error running the selected code generator"

I'm following a video tutorial where I'm required to create an empty ASP.NET Web Application with MVC, using Visual Studio 2015, being new to ASP.NET world, I'm following step by step.
I got my project created well, next step adding a View from an existing Controller, I got hit by a messagebox error saying :
Error :
There was an error running the selected code generator:
'Invalid pointer (Exception from HRESULT:0x80004003(E_POINTER))'
I Googled the problem, found similar issues, but none led to a clear solution, some similar problems were issued by anterior version of VisualStudio, but as I said none with a clear solution.
To clarify what I experienced, here's what I've done step by step :
Chosen a ASP.NET Web Application :
Chosen Empty Template with MVC checked :
Tried to Add View from a Controller :
Some settings ...
The Error :
What's causing this problem and What is the solution for it ?
Update :
It turns out that even by trying to add the View manually I get the same error, adding a view is all ways impossible !
Try clearing the ComponentModelCache, the cache will rebuild next time VS is launched.
Close Visual Studio
Delete everything in this folder C:\Users\ [your users name] \AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache
Restart Visual Studio
14.0 is for visual studio 2015. This will work for other versions also.
I had this issue with a different error message "-1 is outs the bounds of.."
The only thing that worked for me, was to remove the project from the solution by right clicking the project and selecting 'Remove'. Then right click the solution, Add Existing Project, and selecting the project to reload it into the solution.
After reloading the project, I can now add views again.
I have the same error but in VS 2017 when I create a controller. I did it in the same way as #sh.alawneh wrote. Also, I tried to do what #longday wrote. But It didn't work. Then I tried in another way:
Right click on the target folder.
From the list, choose Add => New Item.
There I choose a new controller and it works fine.
Maybe I'll help someone.
Follow these steps to add a view in a different way than the typical way:
1) Open Visual studio.
2) Create/open your project.
3) Go to Solution Explorer.
4) Right click on the target folder.
5) From the list, choose Add.
6) From the child list, choose MVC View Page (Razor) or MVC View Page with layout (Razor).
7) If you select the second choice from the previous step, you should choose a layout page for your view from the pop up window.
8) That's it!
If you cannot open the view that you are created, simply right click on the view file, choose Open with, and select HTML (web forms) editor then okay.
In my case helped the following:
Restart VS
Solution Explorer => Right click on solution => Rebuild solution
I solved this problem in this way
first I had Entity frameworks with the latest version 5.0.5
and the code generation package with version 5.0.2
so I just uninstalled Entity frameworks and install version 5.0.2 as the same for code generation package
and its worked
Right-click on the project under the solution and click unload Project,
you will see that the project is unloaded, so now re right-click on it and press load project
then try to add your controller
Lets assume you are using a datacontext in a DLL, well, it was my case, and I dont know why I have the same error that you describe, I solve it creating a datacontextLocal on the backend project. then I pass the Dbset to the correct datacontext and delete the local (you can let it there if you want, can be helpfull in the future
if you ready are using it in local datacontext, create a new one and then pass the Dbset to the correct one
In ASP.NET Core check if you have the Microsoft.VisualStudio.Web.CodeGeneration.Tools nuget package and it corresponds to your project version.
C:\Users\{WindowsUser}\AppData\Local\Microsoft\VisualStudio\16.0_8183e7d1\ComponentModelCache
Remove from this folder for VS 2019 ....
I am working on a Core 3 app and had this issue pop up when adding a controller. I figured out that the Microsoft.VisualStudio.Web.CodeGeneration.Design package was updated with a .net 4.x framework dll. Updating to the project to Core 3.1 fixed the issue.
just in case someone is interested - the solution with clean cache didnt work for me. but i've managed to solve an issue but uninstalling all .Net frameworks in the system and then install them back one by one.
I just restarted my visual studio and it worked.
Try clearing the ComponentModelCache,
1.Close Visual Studio
2.Delete everything in this folder C:\Users\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache
3.Restart Visual Studio
4.Check again
this also used VS2017 to get solution
I ran into a similar issue that prevented the code generation from working. Apparently, my metadata had unknown properties or values. I must admit I did not try all the answers here but who really wants to reinstall vs or download any of the numerous Nuget packages being used.
Cleaning the project worked for me (Build->Clean Solution) The generator was using some outdated binaries to build the controller and views. Cleaning the solution removed the outdated binaries and voilà.
I'm currently trying to familiarise myself with MVC 4. I've been developing with MVC 5 for a while, but I need to know MVC 4 to study for my MCSD certification. I'm following a tutorial via Pluralsight, targeting much older versions of Entity Framework, and MVC, (the video was released in 2013!)
I hit this exact same error 2 hours ago and have been tearing my hair out trying to figure out what is wrong. Thankfully, because the project in this tutorial is meaningless, I was able to step backward throughout the process to figure out what it was that was causing the object ref not set error, and fix it.
What I found was an error within the structure of my actual solution.
I had a MVC web project set up ('ASP.NET Web Application (.NET Framework)'), but I also had 2 class libraries, one holding my Data Access Layer, and one holding the domain setup for models connecting to my database.
These were both of type 'Class Library (.NET Standard)'.
The MVC project did not like this.
Once I created new projects of type 'Class Library (.NET Framework)', and copied all the files from the old libraries to the new ones and fixed the reference for the MVC web project, a rebuild and retry allowed me to scaffold the View correctly.
This may seem like an obvious fix, don't put a .NET Standard project alongside a .NET Framework one and expect it to work normally, but it may help others fix this issue!
My problem was the Types used in the Model Class.
Using the Types like this:
[NotMapped]
[Display(Name = "Image")]
public HttpPostedFileBase ImageUpload { get; set; }
[NotMapped]
[Display(Name = "Valid from")]
public Nullable<DateTime> Valid { get; set; }
[NotMapped]
[Display(Name = "Expires")]
public Nullable<DateTime> Expires { get; set; }
No longer works in the Code Generator. I had to remove these types and scaffold without them, then add them later.
It is silly, [NotMapped] used to work when scaffolding.
Use the base Types: int, string, byte, and so on without Types like: DateTime, List, HttpPostedFileBase and so on.
I have been scratching my head with this one too, what i found in my instance was that an additional section had been added to my Web.config file. Commenting this out and rebuilding solved the issue and i was now able to add a new controller.
A simple VS restart worked for me. I just closed VS and restarted.
None of these solutions worked for me. I just updated Visual Studio (updates were available) and suddenly it just works.
The issue has been resolved after installed EntityFramework from nuget package manager into my project. Please take a look on your project references which already been added EntityFramework. Finally I can add the view with template after I added EntityFramework to project reference.
Deleting the .vs folder inside the solution directory worked for me.
I know this is a really old thread, but I came across it whilst working on my issue. Mine was caused because I had renamed one of my Model classes. Even though the app built and ran fine, when I tried to add a new controller I got the same error. For me, I just deleted the class I had renamed, added it back in and all was fine.
Check your Database Connection string and if there any syntax errors in the appsettings.json it will return this error.
Another common cause for this, which is hinted in the build log, is your IIS Express Web Server is running while you are trying to build a scaffold. Stop/Exit your web server and try building the scaffold again.
Try unload and reload project (solution).
So, i had this problem in vs2019.
none of the other suggestions helped me
This is what fixed me:
upgrade .net 5.0 dependencies to 5.0.17
I had same error. what I did was to downgrade my Microsoft.VisualStudio.Web.CodeGeneration.Design to version 3.1.30 since my .net version was netcoreapp3.1. This means the problem was a mismatch of the versions.
So check your version of dotnet and get a matching version of Microsoft.VisualStudio.Web.CodeGeneration.Design that supports it.
I had similar proble to this one. I went through 2 appraches for solving this.
First Approach: Not The Best One...
I had created a project on VS2019, and tried to add a controller using VS2022. Not possible. I'd get an error every time.
Error ... Parameter name: searchFolder
Only from VS2019 I'd be able to scaffold the controller I needed. Not the best solution really... But it worked nevertheless.
You could try adding what you need from a different VS version.
Second Approach: The Best One
After further research I found this solution.
From Visual Studio Installer, I added the following components to my VS22 installation:
.NET Framework project and item templates
This made possible to add the controller I needed on VS22.
I know this solution does not point exactly to your problem, but it's maybe a good lead to it. Like you, when I was trying to add/scaffold the controller, I was able to see all the components in the wizard, but in creation after naming it, the error was thrown.
I was also trying. I was facing face problem. I searched on google. I found an error solution. So I am sharing it with you.
You should clear ComponentModelCache in your directory.
1 First Close Visual Studio
2 delete everything from this path
C:\Users\AppData\Local\Microsoft\VisualStudio\15.0\ComponentModelCache
3 Visual Studio Start Again
Hopefully, error will finish

Cannot get both Authentication and Entity Framework working in startup.cs

I am using the most up-to-date code examples and snippets I can find, and I understand that things are changing and moving quickly.
When I use the out-of-the-box Visual Studio "vNext ASP.NET Web Application" template, then authentication and database services work just fine.
However, I think that the template is no longer up-to-date and I would like to use the latest assemblies and methodologies.
If I try to use "Microsoft.AspNet.Security.OAuth" as mentioned here:
https://stackoverflow.com/a/26532837/390480
then I cannot get both Authentication and Entity Framework with SQL Server to work.
What happens is that some methods or properties are no longer available.
Is there any example right now with authentication and EF 7 with SQL working?
Optimally I would like to use UseOAuthAuthorizationServer but that no longer seems to be an option so UseCookieAuthentication is fine.
Thank you.
UPDATE 1:
I have tried the two sample applications "Music Store" and "Identiy Sample".
They would not build/run until I ran the file that comes with them named build.cmd.
So I ran this file but forgot that the last time I ran it it corrupted my system and it corrupted my system again.
Now Visual Studio keeps showing a message box saying:
The project system has encountered an error.
An item with the caption "" already exists in the tree
with the same sort order as the item being added.
Also after running build.cmd I now get hundreds of errors such as:
Error 1 The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
I don't know what fixed it last time. Trying to fix again now.
UPDATE 2:
I remember how I repaired my system now. I recorded the steps here and will try it again now. It's about a 1 hour process.
http://forums.asp.net/p/2013828/5795198.aspx?Re+Can+t+creat+new+project
first get the latest KRE
with Command prompt (run as admin)
#powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/kvminstall.ps1'))"
right click on your project and pick newer version KRE !
http://i.stack.imgur.com/dxGth.png
update all your project.json packages to RC1
i.stack.imgur.com/YYAIe.png
and last part on ASP.Net 5 starter Web Template has migration files under Migration folder
and from beta1 to RC there are some changes happened on method names (like GenerateValuesOnAdd is now GenerateValueOnAdd) need to be fixed
and you are ready to go
**** I prefer to start ASP.NET 5 Empty project and select and test everything Step by Step you can also follow that way too ***
(Sorry I want to do a better job on this but stackoverflow doesn't let me put links or images with my reps)

Breezejs update - Latest version of Breeze.WebApi fails on Metadata

I am building on Hottowel spa template and my solution was working fine for Read, Save and Update. Delete was failing though with "Object reference not set to instance of object". At this point the Breeze.webapi verison was 1.2.0.0. After reading some articles, it was suggested to update the breeze to latest version.
I updated the breeze framework using nuget package manager and now, it fails while parsing the metadata - It says JSON string returned from the server have parsing errors. But when I look at the JSON using JSON formatters in chrome. It looks just fine. This is happening with Breeze.webapi version 1.2.8.0.
Now, if I switch just the breeze.webapi dll back to ver. 1.2.0.0. Metadata part works just fine again, however delete doesn’t.
Any help is appreciated
The likely cause is that the NuGet update did only part of the job and left your application with a mix of new and old Breeze parts. You could see that this happened by looking in the Package Console window but most folks don't look. Having been burned with every NuGet package upgrade I can think of, I now watch that console like a hawk.
I think you'll get out of trouble if you completely uninstall Breeze and re-install the latest. Look at that output window carefully. If it fails to remove something (as it might), there will be a warning to that effect. Please delete that lingering item manually before re-installing.
I'm talking to John about updating the HotTowel template so that upgrading the Breeze package feels less urgent.
Sorry for your pain.

Cannot add a MVC controller VS2012 gives "object reference not set to an instance of an object"

I have searched extensively and cannot find another person on the planet with this problem...
The symptoms are:In Visual Studio 2012, on a MVC 4.0 Project that was upgraded from VS2010 and is configured for dual version editing from VS2012 and VS2010. When I right-click on the Controllers Folder and select Add->Controller... from the context menu, I get an "Object reference not set to an instance of an object" error from Visual Studio.
The existing code in the project runs fine, and if I use the Add->New Item option instead, and pick the Controller from the dialog box, then I can add a blank controller. I just cannot add a typed controller using the method above.
If I however create a new MVC4 Project, then I can add typed controllers again using the same menu, so the problem does not exist in Visual Studio's installation, it has to exist in the Project File. I have also checked the references between my project and a new MVC Project and all the new project references are included in my project.Has anyone experienced something similar?How do I fix this?
The issue seems to have been caused by an incomplete install/registration of the MvcScaffolder package.
The following process resolved my issue for me.
Start Visual Studio and open the project. Open the Package Manager Console. (This was the "trick" or missing piece of information that led to the solution...)
Here I saw the following error caused by the PowerShell script used for registration:
New-Object : Could not load file or assembly 'System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
At <ProjectPath...>\packages\MvcScaffolding.1.0.9\tools\registerWithMvcTooling.ps1:163 char:27
+ $newProvider = New-Object <<<< $powerShellScaffolderProviderType($mvcScaffoldingProvider)
+ CategoryInfo : NotSpecified: (:) [New-Object], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException, Microsoft.PowerShell.Commands.NewObjectCommand
When I checked the registered scaffolders from the Package Manager Console I got:
PM> get-defaultscaffolder
DefaultName ScaffolderName
Action MvcScaffolding.Action
Controller MvcScaffolding.Controller
CustomScaffolder T4Scaffolding.CustomScaffolder
CustomTemplate T4Scaffolding.CustomTemplate
DbContext T4Scaffolding.EFDbContext
Mailer Mailer.Razor
Repository T4Scaffolding.EFRepository
UnitTest MvcScaffolding.ActionUnitTest
View MvcScaffolding.RazorView
Views MvcScaffolding.Views
So clearly the scaffolders are configured to use the MvcScaffolding package, but the package had a registration error.
A quick search for the error provided this link http://mvcscaffolding.codeplex.com/discussions/437692 which refers to https://visioautomation.codeplex.com/discussions/397034 that suggests installing PowerShell 3, which is actually part of the Windows Management Framework 3.0, available from http://www.microsoft.com/en-us/download/details.aspx?id=34595. I picked the Windows6.1-KB2506143-x64.msu file when prompted because I’m running Win 7-64-bit.
Restart the PC after installation, re-open Visual Studio and the project and look at the Package Manager Console. If the error is gone, then so is the controller problem.
I had this problem on VS2012 on Win8, We where working on a project that we started developing on VS2010 and i wasn't able to create new controllers with the CTRL+M, CTRL+C shortcut.
Opening any project and re-installing MvcScaffolder and its dependencies under Manage Nuget package have fixed this for me.
Didn't have to restart VS2012 at all.
Maybe your existing project have wrong ProjectTypeGuids element in .csproj file?
Right one for MVC4 is {E3E379DF-F4C6-4180-9B81-6769533ABE47}.
Try to compare what project type do you have in new project and in your existing project.
The preferred answer of installing the Windows Management Framework 3.0 did not work. The download "Windows6.1-KB2506143-x86.msu" did not work on my Windows 7 32 bit system. It failed with the error "The update is not applicable to your computer".
Reinstalling MVCscaffolding with Manage Nuget Packages did not work.
My ProjectType GUID was correct.
Microsoft Web Developer Tools was already installed.
Deleting and recreating the solution didn't work.
It was necessary to repair the Visual Studio 2012 installation from the install disk to fix this issue.
Installing "Microsoft Web Developer Tools" fixed this for me. Related:
How do I open a csproj with ProjectTypeGuids 349c5851-65df-11da-9384-00065b846f21?
{E3E379DF-F4C6-4180-9B81-6769533ABE47} - MVC4 Project
{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - CSharp Project
{349c5851-65df-11da-9384-00065b846f21} - Web Application Project (this is what you need web dev tools for)
The update Windows6.1-KB2506143-x64.msu worked for me. The problem started after a full SpyWare software scan. I think that it removes more things than the usual. So, back to normal life.
I had the same problem, im using database first, and it was because i have changed the .edmx contex.tt to generate the contex.cs with the connection name set to a custom method,
: base(sqlHelper.getMainConnectionString())
every time, before i change/update the .edmx, i need to change the connection name to it's creation defaults:
: base("name=YourWebconfigConnectionstringName")
rebuild the project and it works again
Answer:
Check your connectionstring string and provider parameters at the webconfig, then delete and recreate the .edmx this will force the generator to rebuild all the database objects, metadata included OR delete all tables in the designer, change the contex.cs to the default creation name, rebuild the project, add the tables, rebuild the project, it shoul work again.
This problem manifested on a target MVC5 project using VS2017.
Like the original op, a new project was attempted to perform an Add Controller with EF scaffolding against ApplicationUser. The error did initially manifest until a single user was registered forcing the database to be created. After that, add scaffolding worked without incident. I think this makes sense because the entity didn't really yet exist before the first registration, although I will stand corrected if someone more knowledgeable than myself has a more accurate explanation. But because Add Controller worked with a new project, just as the original op determined, it didn't seem to be a VS2017 installation problem. This pointed to something wrong with the taret project.
At this point in the target project an Undo All in Team Explorer was executed to get the project back to a previously working point. While this might be accomplished by getting a specific version, for this target project all that was required was an Undo All. A word of caution: in the case of this specific project, before undoing, the Package Manager was used to rollback the database to the starting point that would match with the Undo All. If one performs a get specific version, be sure to check if the database needs to get rolled back to the proper configuration. After resetting all the project changes, the object reference not set to an instance of an object error was no longer present during the Add Controller operation, fixing the error within the target project.
I post this response somewhat reluctantly because I am unable to duplicate the error, and I am unsure of what actually caused the problem in the first place, but this is a particularly nasty error if one is in the middle of a project and Add Controller starts failing. I figured if someone has this problem and rolling back the current change set might fix it for them, like me they will be thankful. If I later determine the pattern of activity that caused the problem to crop up in the first place, I'll surely add more to this post.
I'm running VS 2019 Enterprise, ASP.NET Core 3.1.3.
I was trying to add MVC controller with views using Entity Framework (EF) after scaffolding in database first approach.
I run on this issue because one of the tables in my ER model was missing primary key.
That table was connected to table for which I tried to generate MVC controller through another table that has primary key so I didn't noticed initially that error.

MVC View designer complains "There is no endpoint listening at net.pipe://localhost/

I recently installed Visual Studio 2012 (Ultimate edition) Update 2. I'm not sure if this problem is related to that update but.. now, when I view any of my View (.aspx) code in the VS designer, the initial #model or #using directive gets a squiggly underline and an associated error message of "There is no endpoint listening at net.pipe://localhost/xxx". All of the code in the page that relies on the #model or #using directive gets its own associated squiggly underline errors. But the code runs just fine. The error is in the designer, not in the runtime JIT compiler magic.
Any suggestions?
After a bit more digging, I found a blog post that suggested that the problem might be caused by failing to run VS as administrator. I tried that (I ran VS as administrator and loaded the offending solution) and, bada bing, bada boom, problem solved.
I've been happily skipping the "run as administrator" rigmarole for ASP.NET projects, and everything has worked correctly. I guess they must have changed something in Update 2 that now requires ASP.NET MVC projects to be opened with admin privs.
Can someone who knows better than I confirm this diagnosis?
(BTW, I ran across this post that shows how to force VS to always run with admin privs on Windows 8. This is an all-or-nothing solution... What I'd REALLY like is for the VS developers - or someone with time on their hands - to add a context menu item to .sln files to open them in VS with admin privs enabled.)
EDIT:
4 months after I posted this "solution" (actually, a work-around), here's where I am: I opened an incident with MSDN tech support. After much work, we got nowhere; still no clue what the underlying problem might be. But this problem only exists on my desktop PC - my laptop doesn't have the problem - and I'm buying a new PC, so the problem should go away when I install VS on the new PC and turn the old PC into a doorstop.

Resources