Adding a service reference in ASP.NET MVC 4 - asp.net-mvc

I have two projects: Mvc3TestSvcRef & Mvc4TestSvcRef.
Mvc3TestSvcRef is from the ASP.NET MVC 3 template for an intranet application.
Mvc4TestSvcRef is from the ASP.NET MVC 4 template for an intranet application.
I'm trying to add a service reference.
In Mvc3TestSvcRef, I right-click the project (or the References folder) and choose Add Service Reference. I point to the URL, click Go. When the reference is resolved, I enter a namespace and click OK. As expected, I see the section added to config with the bindings and client tags completed.
I can import: "using Mvc3TestSvcRef.MySvcRef;"
And write code like:
using (var cl = new MyServiceClient())
{
cl.DoStuff();
}
In Mvc4TestSvcRef, I follow the same steps, but there is no system.servicemodel added to config. Additionally the import: "using Mvc4TestSvcRef.MySvcRef;" cannot be resolved.
I've tried this for MVC 4 from both Visual Studio 2010 and Visual Studio 2012.
Was there a major change to the process for adding service references in ASP.NET MVC 4 project type, or am I missing something or have corrupt install?

There was no code in Reference.cs, just comments:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
I copied the reference.cs from the project that worked and modified the namespace, then added the section from the working project into the MVC 4 project and was still having an issue.
I tried to build and I got several warnings and an error. Failed to generate code for the service reference 'MySvcRef'. Please check other error and warning messages for details.
That led me to this article: Service Reference Error: Failed to generate code for the service reference
So I unchecked the Reuse types in all referenced assemblies from the Advanced section.
This seems to have generated a good service reference. Although, I should point out that if you have something in say System, like System.TimeSpan for example, that is used as a DataMember in one of your DataContracts, the reference will now have TimeSpan in the reference namespace, not from it's origin. So, the client would see any System.Timespan properties as ReferenceNameSpace.Timespan, which may throw off comparisons and such. The better answer here is to include specific assemblies from the reference and don't check the box for System.Web.Http, as pointed out in the comments below

I don't know if it is too late, but here is the solution "When you add the reference, on advanced setting remove the reuse types checkbox."

Related

Why is MVC scaffolding failing? (w/ different errors in VS2012 vs VS2013)

I'm leveraging a large existing codebase of business objects and their associated data access layer into an ASP.NET MVC web application. When scaffolding views for the business objects, the scaffolding engine fails with the following message in Visual Studio 2013:
Error
There was an error running the selected code generator:
'The method or operation is not implemented.'
In Visual Studio 2012, the error is:
Error
There was an error running the selected code generator:
'The Extender Provider failed to return an Extender for this object.'
Already tried:
Copying the default templates to a CodeTemplates folder: I got custom templates to work just fine on some POCOs I added directly to the project, but they fail on the real objects I want to use.
Wrapping the CodeTemplates in try/catch blocks with the catch set to write to trace: I tried this method but never got any trace results. I suspect the error is before the template itself starts processing.
Of note, the business objects are split into three partial classes each. The "Model class" select list in the "Add View" window shows three of each class name, but selecting any of the three for any of the business object classes gives the same error.
How can I find out what is causing the actual error and either correct it or find a workaround?
Check what version of EntityFramework are you using, if it is > 6.1.0
turn it to 6.1.0. or lower.
I dont know why it is so, but when i changed version of EntityFramework in my project scaffolding starts work correctly.
In my experiences, most error is either the code haven't compiled yet (It's kinda a weird issue, VS sometimes can't see the class that is not compiled yet), or perhaps different namespace used,
I hope that's really helps

ASP.Net MVC: How to dynamically load assemblies (controllers) without an AppPool restart/recycle

I'm trying to write a module/plugin system for a website I'm working on. The overall goals are:
That the main website does not have to be recompiled every time a new plugin is added.
To be able to dump DLL's and CSHTML files into a set of folders that would basically add a set of routes, controller(s), and any other assemblies that the module depends on (Entity Framework, etc).
To avoid marking plugin files as "embedded resources" -- especially views.
To be able to add and remove these modules/plugins WITHOUT having to restart/recycle the IIS app pool or unload the app domain.
I got #1-3 working by following the example of Umbraco. Basically, I marked a method with the PreApplicationStartMethod attribute, and in it I shadow copy DLLs around, and use a custom ViewEngine to locate the module's CSHTML files. When my website first starts up, my module's controllers and views are working, and assemblies are loaded: Hooray!
However, when it came time to try part #4, I am getting this error when calling BuildManager.AddReferencedAssembly():
This method can only be called during the application's pre-start
initialization phase. Use PreApplicationStartMethodAttribute to
declare a method that will be invoked in that phase
It's been a very frustrating process so far, and my gut tells me that this error signifies a dead end. Is this the case, or is there a clever workaround?
Editing the web.config file when you add the new modules should cause the site to recompile.
You could automate this in a script, forcing your new .dll's to be copied to the live ASP.NET temp files directory.
Check out portable areas. Essentially a regular MVC area (including views, controllers, etc.) gets compiled into a single dll. These dll's (one for each area) can be dropped into a hosting MVC website and can be called like any other MVC area.
Some references to get started:
Portable Areas three years later – Part 5
MvcContrib Portable Areas
"To be able to add and remove these modules/plugins WITHOUT having to restart/recycle the IIS app pool or unload the app domain."
It turns out that this you cannot unload an assembly from an app domain.
How to unload an assembly from the primary AppDomain?

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.

Getting Compilation Error when trying to do Multiple-Project ASP.Net MVC Site

I am getting this error.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1704: An assembly with the same simple name 'MyMVCAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null has already been imported. Try removing one of the references or sign them to enable side-by-side.
My solution has 2 ASP.Net MVC projects - splitting the main content and the areas. The main project doesn't have a reference to the 2nd one. Instead, it gets all MVC DLL's in the folder and stores it into the IOC container, which takes care of registering all the controllers.
I get the error when I set the output of my 2nd ASP.Net MVC project into the bin folder of the main one. (I've set all my views in the Areas solution to Copy Always.)
I also tried post-build action of copying the DLL into the main bin instead of setting the output, but the results are the same.
What should I do?
In addition, I have the following setup:
It is set to use the Local IIS Server instead of the VS Dev Server.
In the Output window, I see that the local web server is loading all the DLL's from the GAC and Temporary ASP.Net files folder. The problem I see is that it is also trying to load my DLL file from my Solutions folder.
Any ideas why it is trying to get that sole DLL from the Solution too? It doesn't have that behaviour for the other projects.
UPDATE:
Here's a strange behaviour:
[1] I clear all copies of the offending assembly.
[2] I removed the post-build action that copies that assembly to my main MVC project bin folder.
[3] I run the main project. It works without any issues, but of course the missing assembly does not get loaded.
[4] I manually copy that assembly to the mian MVC project bin folder.
[5] I run the solution. It is getting the error again!
Can someone explain why it is trying to load this very same assembly from two different places?
Ok this may be a clue to the problem: Because I am copying the assembly to the main MVC project's bin folder, it is also getting copied into the Temporary ASP.NEt folder. At the same time, because the project is not being referenced by any other project in the solution, it is also copying the same assembly into IIS. How can I prevent this from happening? If I exclude the step of copying the assembly into the main MVC bin, it does not get loaded into IIS at all. Why is it behaving that way?
This error points out that two references have the same assembly
identity because the assemblies in question lack strong names, they
were not signed, and thus the compiler has no way of distinguishing
between them in metadata. Thus, the run time ignores the version and
culture assembly name properties. The user should remove the redundant
reference, rename one of the references, or provide a strong name for
them.
Can explain that like below.
Below sample creates an assembly and saves it to the root directory.
// CS1704_a.cs
// compile with: /target:library /out:c:\\cs1704.dll
public class A {}
Below sample creates an assembly with the same name as the previous sample, but saves it to a different location.
// CS1704_b.cs
// compile with: /target:library /out:cs1704.dll
public class A {}
Below sample attempts to reference both assemblies.The following sample generates CS1704.
// CS1704_c.cs
// compile with: /target:library /r:A2=cs1704.dll /r:A1=c:\\cs1704.dll
// CS1704 expected
extern alias A1;
extern alias A2;
UPDATE
If both assemblies are strong-named (signed), the CLR will always load from the GAC.
You can follow below mentioned steps :
Determines the correct assembly version by examining applicable
configuration files, including the application configuration file,
publisher policy file, and machine configuration file. If the
configuration file is located on a remote machine, the runtime must
locate and download the application configuration file first.
Checks whether the assembly name has been bound to before and, if so,
uses the previously loaded assembly. If a previous request to load the
assembly failed, the request fails immediately without attempting to
load the assembly.
Checks the global assembly cache. If the assembly is found there, the
runtime uses this assembly.
Probes for the assembly (for more info check below mentioned article )
for more information check How the Runtime Locates Assemblies
I hope this will help to you.
I had a similar problem playing around with a test container project having added the wrong reference. I removed it and found that after a solution clean and a rebuild the issue was two DLL's in the bin directory clashing. Having removed them and rebuilt everything was fine.

How to use compiled global resources in ASP.NET MVC

I want to compile App_GlobalResources/Strings.resx into my assembly (and eventually use satellite assemblies for Strings.es.resx, Strings.fr.resx, etc.) but the following error occurs once the app is published:
"Could not load file or assembly 'App_GlobalResources' or one of its dependencies. The system cannot find the file specified."
Steps to Reproduce:
Create a new ASP.NET MVC project.
Add an App_GlobalResources folder and a Strings.resx file.
Set the file's build action to 'Embedded Resource'
Add a string to Strings.resx and use it in HomeController.Index(), e.g. ViewData["Message"] = Strings.MyTest
F5 to debug, works fine.
Publish to IIS and (since Strings.resx is excluded from publishing) you will get the above error in the published site.
Can ASP.NET MVC projects use string resources compiled into the dll and if so, what am I doing wrong?
Update: Here is what I see in Reflector:
So why is the ResourceManager not finding them? Isn't it supposed to fallback to the main assembly by default?
Here's a good starting point http://odetocode.com/Blogs/scott/archive/2009/07/16/resource-files-and-asp-net-mvc-projects.aspx
I setup a project just like you mentioned and got precisely the same error when I deployed to IIS6. Changing Custom Tool to PublicResXFileCodeGenerator and Custom Tool Namespace to Resources per Scott's suggestions cleared it right up.
I'd also follows Scott's lead with respect to eliminating App_GlobalResources but I got it to work just fine. That might be a matter of personal preference.
Probably there is one more thing one should know about the PublicResXFileCodeGenerator - it does not work with files that has more then one dot in the file name (see http://social.msdn.microsoft.com/Forums/ru-RU/9412f049-acd8-4a77-b73a-f3810df18376/naming-resources-files-issue-aspnet-mvc-3?forum=dlr). So the codebehind for the Strings.es.resx, Strings.fr.resx, etc. remains empty. The easy solution is to rename the files.

Resources