Two routes after namespace refactoring MVC WebAPI - c#

i renamed my namespace for my whole project. Everything is still working fine, but my WebAPI is now finding two routes for my controllers.
Multiple types were found that match the controller named 'department'.
This can happen if the route that services this request ('api/{controller}/{id}') found multiple controllers defined with the same name but differing namespaces, which is not supported.
The request for 'department' has found the following matching controllers:
A***.P***.Benutzerverwaltung.Jo***MVC.Controllers.DepartmentController
A***.Benutzerverwaltung.API.Controllers.DepartmentController
So i renamed the first namespace into the second, i searched everywhere for the old namespace, but nothing was found. So, what could i do?
Thanks for help.

So, what could i do?
Go to the bin folder of your web application and delete the old assemblies. ASP.NET loads all assemblies that are present in the bin folder. So if you are saying that you renamed some class library project reference, the old assembly is still physically there.

Related

Issue with sharing MasterPage between projects in Solution

My team has multiple web application projects that have common components. In order to keep from having multiple instances, we have setup a common source that contains common classes and web project. In the web project, we would have MasterPage, pages, and user's controls that are shared as linked files from the main web application. each of the shared projects are included as part of the solution. The solution builds successfully, but when I open the page of the web app, I'm getting server stating that "The type 'Common.Controls.Master' is ambiguous: it could come from assembly 'C:....\bin\Common.Controls.DLL' or from assembly 'C:....\bin\AppWeb.DLL'. Please specify the assembly explicitly in the type name."
The actual Common.master resides in the Common.Controls project at the root. The link file to the master page is in the AppWeb project.
I've looked for solution and found this How to share Master Pages between my projects which is pretty much what I'm doing.
Another option I found was What is the best way to share MasterPages across projects. I haven't tried the methods in this one.
I was certain that using the linked file would work.
Thanks in advance in helping me resolve this error.
I faced a very similar issue recently with a different shared class.
Is it possible that the initial location of the MasterPage was under AppWeb project and then moved under Common.Controls project? In this case a build would not clean the previous dlls and would cause the error you are looking at. If this is the case, a simple manual deletion of all files under the bin folder of your projects and rebuild should solve the issue.
I hope this helps

Web Api controller thinks it is duplicated

I have a webforms app, that has some Web Api controllers in it for integrations.
Two are working just fine. But Today I wanted to add another controller.
Should be simple enough, I add a new Web Api controller, add a little bit of code to it, and:
namespace MyApp.Web.App_Code
{
public class AuthExportController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
and when i call it at this url :
http://localhost:30978/MyApp/api/AuthExport
I get this error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Multiple types were found that match the controller named
'AuthExport'. This can happen if the route that services this request
('api/{controller}/{id}') found multiple controllers defined with the same name but
differing namespaces, which is not supported. The request for 'AuthExport' has found
the following matching controllers: MyApp.Web.App_Code.AuthExportController
MyApp.Web.App_Code.AuthExportController</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace> at
System.Web.Http.Dispatcher.DefaultHttpControllerSelector.SelectController(HttpRequestMessag
e request) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage
request, CancellationToken cancellationToken) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken)</StackTrace>
</Error>
As you can see, it is complaining about 2 controllers with the same name, but its the exact same controller. My other controllers work fine, just this particular one.
If it helps anything, this is my routing code in global.asax
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
}
Driving me mad!
Update:
Ok I managed to fix it, but I don't understand why, so if someone could explain it to me.
I compared my working controllers with my non working one.
Exact same signatures exactly, nothing different, same using statements, same inheritance etc etc.
One thing I did notice is the build action on the file.
Working file has a build action of "Content" and the non working has a build action of "Compile" . I change my non working one to "Content" and it works.
So now I am even more confused :) Happy that it works, but I don't like black magic in my systems
TL;DR:
Delete bin folder in your project's file directory and build your project again.
Explanation:
I just encountered this error while renaming an existing project and changing namespaces for it and this is what happened:
Let's say projects' name was FirstName and I wanted to rename it to SecondName.
I built project which compiled everything and generated bin/Debug/FirstName.dll files
I renamed the project to SecondName
I refactored the namespace
Built and ran the project
This generated bin/Debug/SecondName.dll
When project was ran, IIS Express simply took all of the .dll files and loaded them into memory, which happened to include both FirstName.dll and SecondName.dll.
As you might already understood, FirstName.dll and SecondName.dll had the same classes and methods, but with a different namespaces!
Therefore, as both of DLLs were loaded into memory by IIS, WebApi routing mechanism was finding both of namespaces with same controllers and action names.
And there you have it. No voodoo magic after all :)
I had to change names of references, projects and solution and after that I had this problem for days.
When I looked for solution, I got the answer everywhere that remove your /bin folder contents and try rebuilding solution, I did that but this didn't solve my problem.I then created a separate solution added all these projects in that solution with bin folder empty, and build the solution still didn't solve my problem.
Here are the things I had to do to get back on track:
First changed assembly names from Project/Properties/
Cleared /bin , /bin/debug folder
Cleared /obj/debug/(.dll, .cache, temporary created files) of each project.
Then rebuild the solution and finally got it solved.
If removing only /bin doesn't work out then try this.

ASP.Net MVC Controller cannot see another namespace

I have an MVC Controller that cannot see another namespace in the using statement.
Specifically this line of code:
using TRN.Website.Tools;
Errors with:
The type or namespace name 'Tools' does not exist in the namespace
'TRN.Website' (are you missing an assembly reference?)
Other parts of my project can see the TRN.Website.Tools namespace however.
I tried adding the namespace to web.config but this had no effect.
EDIT: Sorry all I have missed out a vital bit of information. TRN.Website.Tools is just a folder with the namespace TRN.Website.Tools in the same project. It is not a separate project or a dll.
My guess: You have multiple projects in you solution and you have multiple libraries (dlls) that their names starts with TRN.Website and you added reference to one of these dlls in your MVC project. you have to add reference to the other one too.
Solved but in a really strange way.
I added another class in the Tools folder and after that the error disappeared.
Very very odd.
Check your Build Action of your class in properties window. It must be 'Compile'.
Your ASP.NET MVC project does not contain a reference to the assembly that contains the TRN.Website.Tools namespace. You have to reference that from your ASP.NET MVC project in order to use it.
If TRN.Website.Tools is a project in your Solution, you can just add a Project reference to it.
If it isn't a project in your Solution, you'll have to add a reference to the compiled DLL to your ASP.NET MVC project.
In my case, I had not checked in the "X.csproj" file to TFS, so the new controller I created was not being found in my testing environments as a valid controller.

Type or namespace could not be found from App_code folder

I have written a class called ArchivedFilesWrapper in the App_code folder of my project, however when I use this class in another file in a different folder i get error:
The type or namespace name 'ArchivedFilesWrapper' could not be found (are you missing a using directive or an assembly reference?)
I thought every page should be able to find classes that are contained within the same project, but I guess this is not the case. Can someone please tell me what using statement I need to have?
Here is a snippet from my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EMCWebAdmin.App_Code
{
public class ArchivedFilesWrapper
{
Perhaps the problem will be solved by changing the Build Action Property of the *.cs source file to Compile from Content. From the Solution Explorer right click on the source file and choose Property.
Note that the App_Code folder is intended for use in Web Site Projects.
Note that for a Web Application Project or MVC project, adding an App_Code folder to your project and putting *.cs files in it will cause problems. I ignorantly added an App_Code folder to my MVC project from the Solution Explorer. VS defaulted the name space to MyProjectName.App_Code. In this case Visual Studio 2012 defaulted the Build Action to Content, even though the type was .cs code. After I changed Build Action Property of the *.cs source file to Compile from Content the namespace was resolved in other folder locations of the project. However because of problems, I had to change the name of folder--see below.
Important
In the MVC or Web Application project, the App_Code folder is trouble because it has Web Site Project type semantics. This folder is compiled when published (deployed) to the server. By changing Build Action from Content to Compile, you resolve the namespace issue on your development environment by forcing immediate compilation, but you get trouble when the second compilation results in objects defined twice errors on deployment. Put the code files in a folder with a different name. If you converted a Web Site to a Web Application, see the guidelines on the Net for this--not in the scope of this question. To read more about App_Code folder in the different project types see this blog
You need to add
using EMCWebAdmin.App_Code;
to all the pages you want to be able to use the class.
Alternatively you change the namesspace that the class is in to the same one that all the web pages use which presuming it is EMCWebAdmin
then in your class change
namespace EMCWebAdmin.App_Code
{
...
to
namespace EMCWebAdmin
{
...
This is a feature of visual studio, if you create a class in a folder structure, it uses a namespace that follows the folder structure.
If you convert it to a web app it should work. The downside is that it will no longer autobuild your code in app_code folder every time you change it and spin up the app. I have never seen a professional developer use a website project. I have no idea who MS were targeting when they created them.
Yes, put the calsses to another folder(not asp.net special folder), and only use the main namespace for the application is solve this issue.
Thanks johnmcp.

Compilation errors in Reference.cs after adding a Service Reference caused by multi-part namespace

I hit this weird namespace issue when adding my first 'Service Reference' to a client project in Visual Studio 2010.
If my project's default namespace uses two or more parts, e.g. MyCompany.MyApp then when adding a Service Reference a Reference.cs file is created containing the namespace MyCompany.MyApp.ServiceReferenceName with a lot of auto-gen code with fully qualified names, e.g. System.SerializableAttribute, System.Runtime.Serialization.DataContractAttribute.
The Reference.cs file will be full of compilation errors because the compiler starts treating the System namespace as sub member of the MyCompany.MyApp namespace. You get an awful lot of errors along the lines of:
The type or namespace name 'Runtime' does not exist in the namespace 'MyCompany.MyApp.System'...
If I amend the namespace at the top of the Reference.cs file to something simple, e.g. MyCompanyMyApp.ServiceRefernceName then the compiler behaves and recognises the System namespace references as decleration of .net's System namespace.
I'm using a different workaround for now as I really want to keep my multi-part namespaces. My current alternative is to append global:: in front of the System namespace references to force the complier to do the right thing. In fact, if the 'Add Service Reference' wizard uses T4 templates I may just amend those to embed my workaround at the source.
Questions
I'd really like to understand what's going on here and why a multi-part namespace causes this issue. Presumably there's more to namespaces than I thought. Secondly, would really like to work out a better solution than performing a global Find/Replace every time I add a Service Reference or mucking around with some T4 templates.
I found the answer here somewhat unclear, so I thought I would add this as an example (I would do it in the comments but it looks better here):
So I have this as my default namespace:
namespace RelatedData.Loader
But I also add a class named:
public class RelatedData
{
}
Because the class name matches a portion of the namespace when it generates your proxy with Add Service Reference it gets confused.
The answer here was to rename my class:
public class RelatedDataItem
Ahh well I found the cause eventually.
I'm working against a very large third party WCF API and ... one of their namespaces is LameCompany.System (!!) Carnage then ensues...
Arrrgghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
The lesson to learn here is when Visual Studio/.net compiler stops recognising the BCL's System namespace you have a namespace/type in your project called System. Find it, remove it, shoot the developer that created it.
I found that having a class name similar to your namespace causes this.
Try renaming your class name
I ran into a similar issue with VS2012 described by jabu.hlong and Simon Needham after minor changes in the client project that has the references to the WCF services after updating the reference to the services. I got lots of errors compiling the Reference.cs files generated and so on (the generated files of the XAML as well).
I have selected to reuse types from specific assemblies in my solution and got a similar problems with the namespaces.
The error I get is that the namespace of the reused assembly and the namespace of the generated types can not be found when used in the Reference.cs. Both namespaces have in common the first parts, as they are from the same solution. My namespaces in the solution are like appname.tier.technology.project. Both conflicting namespaces are Appname.Dto.Modulename (the reused assembly) and Appname.Client.Wpf.ServiceName (the namespace in the client project using the services for the generated types).
The problem arises after a minor change in the client project, when I created a new utility class in the namespace Appname.Client.Wpf.Appname. I choose that namespace because the Appname is also the name of a module in the client project. This seems to confuse the compiler and can not resolve both namespaces in the generated Reference.cs. After changing the namespace of the utility class to avoid using two identical parts in it and updating the service reference, the compiler errors in Reference.cs dissapears.
I tried different things (and tried different namespaces when adding the service reference), but nothing worked for me except this brute force fix - in my case it was OK but I am aware it's ugly (and needs to be repeated if you use "Update Reference" in the future):
Since the WCF service namespace is added to your default namespace, just search and replace all mentions of the newly added
MyNamespace.ServiceNamespace
with
ServiceNamespace
in the whole solution (use your own namespaces of course), including the auto-generated Reference.cs file.
Basically, the problem is a name conflict where one name is hiding another. A folder or class named "System" can do that, but if you also have a class with the same name as your project, you'll see the same thing. Sure, you can rename everything in the reference.cs, but it's probably better to rename your conflicting class.
I had folder in my project called "System" (yes, very stupid of me) and that caused some issues in the references.cs.
Renaming the folder (and the namespace), fixed the issue.
Here is how I solve this issue on VisualStudio 2017 trying to add a reference to a web service in a test project.
After trying adding the references, rebuilding, closing, reopening and spending some time on the issue, I noticed that VS had put the files it creates to reference the WS in a folder named "Connected Services".
I renamed the folder without the space then opened all the files in the folder and the csproj with a text editor, replaced all the occurrences of "Connected Services" to "ConnectedServices" and reopened the project.
I then added references to System.Runtime.Serialization and System.ServiceModel and everything now works fine.
This is a bug in Visual Studio (still is at version 2022). To fix, remove the namespace in the reference.cs file. So if your namespace is "myapplication" and your service is "myservice", you'll see myapplication.myservice in the reference.cs file. just delete "myapplication." everywhere and make sure it isn't auto-generated again (lest you have to re-delete everything).

Categories