Related
I am in the process of learning ASP.NET Core MVC, while experimenting, I noticed that when I try to refactor the code using the built in refactoring tools provided by Visual Studio they don't work very well. For example:
Renaming a class via the solution explorer pane usually fails. When it succeeds it will fail to rename the class on the view declaration (eg: #model ClassNameIsNotRenamed);
If I rename a controller or action, the helper tags such as asp-controller="NotRenamed" and asp-action="NotRenamed" do not get updated.
etc.
I don't want to get too detailed on what works and what does not work, the point that I am trying to make is that VS 2017 does not appear to do a good job when it comes to refactoring.
So my question is... Am I asking to much from VS 2017? Is there something that I can do to make refactoring work better?
Thanks.
Doing something like a rename requires that your project can build successfully. If you attempt rename something like a class, and the project either hasn't been built or failed the build, the rename will fail as well. This is fairly logical, as doing a rename refactor requires tracking references, which it can't do without the IL.
As far as your Razor views and controller/action references go, you're dealing with strings and/or code that is not compiled. As a result, it doesn't participate in code-based refactoring generally. Certain things like renames give you option to search strings as well, which you can do to catch more places where things should be renamed, such as your controller/action references. However, that can also cause unwanted side effects if you happen to be using the same string somewhere else, in a different context (which is why string replacement is not done by default).
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
I have a MVC5 project that is currently set on the "Release Configuration" and it works 100%. However, as soon as I switch the project configuration from Release to Debug, then everything goes wrong... even if I switch it back to Release mode, everything is still broken. Only way I can get the project working again is to restore from a backup.
Here are what is happening.
Firstly, when running the project, I get the following error:
BC30451: 'ViewData' is not declared. It may be inaccessible due to its
protection level.
If I open any view in the project with Visual Studio 2013, I can see that all sorts of things are marked as errors like ViewData, Html, Url, etc.
When referring to #Html or #ViewData in the view, it normally refers to the .Html and .ViewData properties of the view's base class (WebViewPage). However, if I start typing "#Html." in any of the views, I can see in the autocomplete that it is referring to the System.Web.Webpages.Html namespace instead of the WebViewPage.Html property. It is as-if the view isn't inheriting from the System.Web.Mvc.WebViewPage class.
Any guidance as to where I can start looking to get this fixed or why this is happening?
Edit:
So since nobody responded, I went through the long way. I created a brand new MVC5 project, added all the packages via Nuget and then simply copied all my files over from the old project to the new one and now it works.
Does anybody have any idea what the heck could be causing this? I don't want to go through all this trouble again in the future if the project again suddenly decides to stop working.
Ok, I think I've found part of the cause here. Thing is, since the original code is valid (it compiles correctly and intellisense picks it up) and the code used to work and then all of a sudden, one day after compiling, it just stops working.
Anyway, in the view, when specifying the ModelType, if you don't use the full name, this error can occur or occurs eventually.
For example, using:
#ModelType Models.SomeNamespace.SomeClass
will cause the error (even though the Root Namespace for the project is "MyProject") and it can be fixed by simply specifying the full namespace and class name.
#ModelType MyProject.Models.SomeNamespace.SomeClass
It's possible that a debug assembly is locked. Can close Visual Studio, search and delete for all bin folders in the solution directory. Then open and rebuild.
The other options is to go into the MVC project properties and compare the two build configurations. Are you targeting a different .NET framework between Release and Debug? 32 bit vs 64 bit? etc?
Looks like some MVC assemblies are corrupted.
Have you checked your referenced assemblies for some errors?
Try also cleaning all the .NET internal cache. More in this stackoverflow topic: Could not load file or assembly ... The parameter is incorrect
In my case imported ViewModel class name was incorrect, correcting it fixed the issue.
I’ve created a new C# asp.net mvc 4.0 (beta) Internet Application and I’m having a somewhat odd behavior in the Add View dialog in Visual Studio 2010 (sp1).
When I decide to create a strongly-typed View, inside the Add View dialog, the Model class dropdown does not show my ViewModel class.
For the record, yes I did compile the application before triggering the Add View dialog.
I believe I have pinpointed the issue but do not know how to fix it.
Below are the repro-steps if anyone cares to reproduce the behavior:
In Visual Studio 2010 (sp1), create a new C# asp.net MVC 4.0
(beta) Internet Application.
Inside the Models folder, create a new simple class called
“GazouViewModel.cs”
Build the application, open the HomeController, right-click the
Index() ActionResult and select Add View…
In the Add View dialog, check the “strongly-typed view” checkbox and
in the Model class: dropdown, you’ll notice your “GazouViewModel”
In Solution Explorer, right-click your project and select “Manage
NuGet Packages”
Search, find and install the “Bootstrapper.Autofac” package.
Rebuild the application and verify if your “GazouViewModel” still
displays inside the Add View dropdown’s dialog.
The “GazouViewModel” should still be displaying in the dropdown.
In Solution Explorer, right-click your project and select “Manage
NuGet Packages”
Search, find and install the “Autofac ASP.NET MVC4 (Beta)
Integration” package.
Rebuild the application and verify if your “GazouViewModel” still
displays inside the Add View dropdown’s dialog.
The “GazouViewModel” should still be displaying in the dropdown.
In Solution Explorer, right-click your project and ADD a new class
(Class1.cs) anywhere it doesn’t matter.
Make that Class1 implement IAutofacRegistration and implement the
interface.
Rebuild the application and verify if your “GazouViewModel” still
displays inside the Add View dropdown’s dialog.
The “GazouViewModel” is no longer showing inside the Model class
dropdown.
It appears that as soon as I create a class that implements the IAutofacRegistration interface and build the application, I’m no longer capable of viewing my ViewModels in that dropdown.
Can anyone confirm if they are getting the same results as me?
And more importantly, how can one fix this?
IMPORTANT: I have tried the exact same steps with an mvc 3.0 application and the exact same behavior occurs…so this is not relevant to the BETA version.
Sincerely
Vince
If you get error message: "Running transformation: The input file appears to be using a schema version not supported by this template. This may lead to compile errors. Please use 'Add New Generated Item' to add an updated template".
You are used EF 5.x. You have to add metadata for EF 5.x to your T4 template. In file header call DefineMetadata()
<## template language="C#" debug="false" hostspecific="true"#>
<## import namespace="System.Text.RegularExpressions" #>
<## include file="EF.Utility.CS.ttinclude"#><## output extension=".cs"#><#
DefineMetadata();
at the bottom of your template create method
private void DefineMetadata()
{
TemplateMetadata[MetadataConstants.TT_TEMPLATE_NAME] = "CSharpDbContext.Types";
TemplateMetadata[MetadataConstants.TT_TEMPLATE_VERSION] = "5.0";
TemplateMetadata[MetadataConstants.TT_MINIMUM_ENTITY_FRAMEWORK_VERSION] = "5.0";
}
I solved this issue by beeing mad in like 2 hours and then deleting the Assembly.cs from the Properties-folder in the solution. After I made a rebuild of the solution, the "Add-view" model-dropdown suddently could find all my ViewModels, strange enough.
I guess the assembly version defined in Assembly.cs somehow got mixed up with the actual version used in the project. Anyhow, it works now for my case.
What worked for me was to simply build the solution after creating my model. Then I was able to find my model in the dropdownlist.
I've noticed this issue as well (using MVC 4 Beta on Visual Studio 2010). Re-starting Visual Studio solved the problem for me.
Just another solution to add to the pile as none of the other ones worked for me. This is another example of Visual Studio being terrible at handling long file paths and namespaces.
In my case the namespace was too long to display in the "Model class" dropdown. Shortening the namespace (a ridiculous pain in of itself) made the drop down work again!
UPDATE: As of this writing, I can no longer reproduce the error. Perhaps the NuGet packages I use have been updated to a newer version and incidentally fixed the error.
I will mark this post as closed.
Thanks for everyone’s input on this!
Vince
Just Clean and build your solution. It worked for me.
Using VS 2010 and MVC 3.0, at one point the Add View Model class dropdown was not showing any classes for me. Ivan's suggestion of restarting VS appeared to work for me.
I tried deleting AssemblyInfo.cs, did a Clean, and a Rebuild, but those didn't resolve the issue. When I restarted VS, the model classes were back in the dropdown.
I realize this is a bit out of date. I had a similar situation where my classes wouldn't load into the View Template wizard. I'm using VS 2012 with MVC3. Everyone else in the team was OK, just luckily old me had issues. After much research and trying lots of things the only thing that has consistently fixed it is running VS in safemode (from the command prompt: "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /safemode). One of my extensions must be causing the issue and by running in Safe Mode those aren't loaded.
What is the easiest language to build Windows services in?
Easiest in this case would be defined as least amount of code, and lowest point of entry into the language.
At the risk of stating the obvious, if you have any C/C++/Java background, I think C# offers you the lowest point of entry.
Assuming you're using Visual Studio 2008, you can follow these steps:
Open Visual Studio 2008, and select the File|New|Project menu option.
In the New Project dialog...
Select the Visual C#|Windows node in Project types
Select the Windows Service template
Enter a name and location for your project
Press OK
At this point, you have all the basics for your Windows service. The Program.cs file contains the Main() method for your service, and Service1.cs defines the System.ServiceProcess.ServiceBase component that is your new Windows service.
In the Property Grid for your Service1 component, consider setting the following properties at a minimum:
(Name) - give your object an intuitive name, e.g., ServiceExample
AutoLog - set to false to prevent events from being written by default to the Application event log (Note: I'm not saying you shouldn't log service events; I just prefer writing to my own event log instead of the Application log - see below)
CanShutdown - set to true if you want to handle system shutdowns
ServiceName - defines the name by which your service will be known to the Service Control Manager (SCM)
In the code for ServiceExample, the OnStart() and OnStop() virtual functions are stubbed out. You'll need to fill these in with whatever your service needs to do obviously. If you changed the CanShutdown property to true, you'll want to override the OnShutdown method as well. I've created an example below illustrating the use of these functions.
At this point, the ServiceExample service is essentially complete, but you still need a way to install it. To do this, open the ServiceExample component in the designer. Right-click anywhere in the designer panel, and select the Add Installer menu option. This adds a ProjectInstaller component to your project, which contains two additional components - serviceProcessInstaller1 and serviceInstaller1.
Select the serviceProcessInstaller1 component in the designer. In the Property Grid, consider setting the following properties:
(Name) - give your object an intuitive name, e.g., serviceProcessInstaller
Account - select the LocalService account as a minimum, but you may have to use the NetworkService or LocalSystem account if your service requires more privileges
Select the serviceInstaller1 component in the designer. In the Property Grid, consider setting the following properties:
(Name) - give you object an intuitive name, e.g., serviceInstaller
Description - the service's description which will show up in the SCM for your service
DisplayName - the friendly name for your service which will show up in the SCM for your service
ServiceName - make sure this is the same name that you selected for the ServiceName property of your ServiceExample component (see Step 4)
StartType - indicate if you want the service to start automatically or manually
Remember that I said I prefer writing events to my own event log instead of the Application event log. To do this, you'll need to replace the default EventLogInstaller in your ProjectInstaller with a custom one. Make your code for your ProjectInstaller look like this:
using System.Diagnostics;
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
EventLogInstaller installer = FindInstaller(this.Installers);
if (installer != null)
{
installer.Log = "ServiceExample"; // enter your event log name here
}
}
private EventLogInstaller FindInstaller(InstallerCollection installers)
{
foreach (Installer installer in installers)
{
if (installer is EventLogInstaller)
{
return (EventLogInstaller)installer;
}
EventLogInstaller eventLogInstaller = FindInstaller(installer.Installers);
if (eventLogInstaller != null)
{
return eventLogInstaller;
}
}
return null;
}
}
At this point, you can build your project to get your Windows service executable. To install your service, open the Visual Studio 2008 command prompt, and navigate to the Debug or Release directory where your executable is. At the command prompt, type the following: InstallUtil ServiceExample.exe. This will install your service on the local machine. To uninstall it, type the following at the command prompt: InstallUtil /u ServiceExample.exe
As long as your service is not running, you can make changes to your service and re-build, i.e., you do not have to uninstall your service to make changes to it. However, you will be unable to overwrite the executable with your fixes and enhancements as long as it is running.
To see your service in action, open the ServiceExample.cs file and make the following changes:
using System.Diagnostics;
public partial class ServiceExample : ServiceBase
{
public ServiceExample()
{
// Uncomment this line to debug the service.
//Debugger.Break();
InitializeComponent();
// Ties the EventLog member of the ServiceBase base class to the
// ServiceExample event log created when the service was installed.
EventLog.Log = "ServiceExample";
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("The service was started successfully.", EventLogEntryType.Information);
}
protected override void OnStop()
{
EventLog.WriteEntry("The service was stopped successfully.", EventLogEntryType.Information);
}
protected override void OnShutdown()
{
EventLog.WriteEntry("The service was shutdown successfully", EventLogEntryType.Information);
}
}
Once you run your service with these changes, you can look at the ServiceExample event log in the Event Viewer and see the messages logged there.
EDIT: If you prefer to use the Application event log for your event logging instead of a custom one, simply make no changes to the ProjectInstaller.cs file. In addition, leave out the line that sets the Log property of the EventLog in the ServiceExample constructor. When you run your service, your log messages will appear in the Application event log.
I agree with everyone that has responded elsewhere, but I would say don't focus too much on the actual language, as long as you're working in the .NET framework, and there's a starter project for you, you're good to go. I've done several "Windows services" in the past, and developed them both in VB.NET and C#, with minimal code.
What I would recommend the OP to do is to learn how to build the installer package for it. Installing the service is as easy as executing "installutil.exe {drive}\path\to\file.exe", but when you have to do anything larger than deploying a "hello world" Windows service, it's good to know and understand how do deploy the service in a meaningful way.
Not to start a flame war, but I've "standardized" on using WiX for all my deployment packages, outside of doing old-school COM interop type stuff, since that's a brunt of work to get to install correctly. I'm anxious for the WiX team to develop the bootstrapper piece that allows you to put the prerequisites and the main msi into an EXE file which can be downloaded. They have it slated for 3.5, so I'll patiently wait, and use WinZip Self-Extracting executables for now.
For me, and I've only tried it a couple of ways, Visual Studio and C# was the easiest.
Visual Studio did all of the necessary service plumbing setup for the framework and I found C# very easy to learn, migrating from VB6, VB.NET and C.
With Visual C#, you'll find the most code samples on the net.
Combined with Visual Studio, and it's a walk in the park to get a basic Windows Service up and running.
Visual Studio also makes it a snap to create a MSI installer package.
That would be my pick
A windows service project in C# will give you a fully deployable service from the Visual Studio template with the click of a button. You just need to add your payload code.
Use the Visual Studio Service type project, use C# or VB.NET.
I personally prefer C#, but in general it's easy to understand the life cycle and code the logic at the desired stage.
Building an installer is also very easy.