[c#] Sometimes adding a WCF Service Reference generates an empty reference.cs

Sometimes adding a WCF Service Reference generates an empty reference.cs and I cannot reference the service anywhere in the project.

Has anyone encountered this?

This question is related to c# .net wcf

The answer is


As the accepted answer points out, a type reference issue when reusing types is probably the culprit. I found when you cannot easily determine the issue then using svcutil.exe command line will help you reveal the underlying problem (as John Saunders points out).

As an enhancement here is a quick example of using svcutil.

svcutil /t:code https://secure.myserver.com/services/MyService.svc /d:test /r:"C:\MyCode\MyAssembly\bin\debug\MyAssembly.dll"

Where:

  • /t:code generates the code from given url
  • /d: to specify the directory for the output
  • /r: to specify a reference assembly

Full svcutil command line reference here: http://msdn.microsoft.com/en-us/library/aa347733.aspx

Once you run svcutil, you should see the exception being thrown by the import. You may receive this type of message about one of your types: "referenced type cannot be used since it does not match imported DataContract".

This could simply be as specified in that there is a difference in one of the types in the referenced assembly from what was generated in the DataContract for the service. In my case, the service I was importing had newer, updated types from what I had in the shared assembly. This was not readily apparent because the type mentioned in the exception appeared to be the same. What was different was one of the nested complex types used by the type.

There are other more complex scenarios that may trigger this type of exception and resulting blank reference.cs. Here is one example.

If you are experiencing this issue and you are not using generic types in your data contracts nor are you using IsReference = true, then I recommend verifying for certain that your shared types are exactly the same on your client and server. Otherwise, you will likely run into this issue.


The following is not listed here, and it was the solution I adopted (SvcUtils was useful in seeing the error message. However, the error I got was wrapper type message cannot be projected as a data contract type since it has multiple namespaces. Meaning, I followed this lead, and learned about wsdl.exe via this post).

In my case, simply running wsdl [my-asmx-service-address] generated a problem-free .cs file, which I included in my project and instanced to use the service.


Follow these steps:

  1. Remove Service Reference
  2. Close Visual Studio
  3. Delete /Bin and /Obj folders.
  4. Open Visual Studio.
  5. Add the Service Reference.
  6. You're Welcome :)

It seems that some references are left in these folders when adding the service, causing errors during the auto-generation of code.


When attempting to troubleshoot this problem with svcutil, I received the error referred to in dblood's answer ("referenced type cannot be used since it does not match imported DataContract").

In my case the underlying cause seemed to be an enum type that had the DataContract attribute, but whose members were not marked with the EnumMember attribute. The problem class svcutil pointed at had a property with that enum type.

This would fit better as a comment to dblood's answer, but not enough rep for that...


I faced similar issue yesterday during development. I found out I was using same namespace in 2 different versions of contracts.

We've 2 version of contracts for example version4 and version5. I've copied all the contracts from version4 and renamed all the namespace from version4 to version5. While doing this I forgot to rename the namespace from v4 to v5 in one of the files. Due to namespace conflict, Reference.cs file was empty.

This issue is hard to troubleshoot as you don't get any error message while generating the service reference. To identify this issue I'd manually validate all the new files I'd created. There are other ways to solve this issue. This is the first step you should perform before going for other options.


When this happens, look in the Errors window and the Output window to see if there are any error messages. If that doesn't help, try running svcutil.exe manually, and see if there are any error messages.


In my case I had a solution with VB Web Forms project that referenced a C# UserControl. Both the VB project and the CS project had a Service Reference to the same service. The reference appeared under Service References in the VB project and under the Connected Services grouping in the CS (framework) project.

In order to update the service reference (ie, get the Reference.vb file to not be empty) in the VB web forms project, I needed to REMOVE THE CS PROJECT, then update the VB Service Reference, then add the CS project back into the solution.



I've been bashing my head for a whole day with this exact problem. I've just fixed it. Here's how...

The service had to run over SSL (i.e. it's at https://mydomain.com/MyService.svc)

Adding a service reference to the WCF service on a development server worked just fine.

Deploying the exact same build of the WCF service on the live production server, then switching to the client application and configuring the service reference to point to the live service displayed no errors but the app wouldn't build: It turns out that the service reference's Reference.cs file was completely empty! Updating the service reference made no difference. Cleaning the solution didn't help. Restarting VS2010 made no difference. Creating a new blank solution, starting a console project and adding a service reference to the live service exhibited exactly the same problem.

I didn't think it was due to conflicting types or anything, but what the heck - I reconfigured the WCF service reference by unchecking "Reuse types in all referenced assemblies". No joy; I put the check mark back.

Next step was to try svcutil on the reference URL to see if that would help uncover the problem. Here's the command:

svcutil /t:code https://mydomain.com/MyService.svc /d:D:\test

This produced the following:

Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation.  All rights reserved.

Attempting to download metadata from 'https://mydomain.com/MyService.svc' using WS-Metadata Exchange or DISCO.
Error: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Schema with target namespace 'http://mynamespace.com//' could not be found.
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://mynamespace.com//']/wsdl:portType[@name='IMyService']


Error: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='http://mynamespace.com//']/wsdl:portType[@name='IMyService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='WSHttpBinding_IMyService']


Error: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='WSHttpBinding_IMyService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:service[@name='MyService']/wsdl:port[@name='WSHttpBinding_IMyService']


Generating files...
Warning: No code was generated.
If you were trying to generate a client, this could be because the metadata documents did not contain any valid contracts or services
or because all contracts/services were discovered to exist in /reference assemblies. Verify that you passed all the metadata documents to the tool.

Warning: If you would like to generate data contracts from schemas make sure to use the /dataContractOnly option.

That had me completely stumped. Despite heavy googling and getting really rather cross, and reconsidering a career as a bus driver, I finally considered why it worked OK on the development box. Could it be an IIS configuration issue?

I remoted simultaneously into both the development and live boxes, and on each I fired up the IIS Manager (running IIS 7.5). Next, I went through each configuration setting on each box, comparing the values on each server.

And there's the problem: Under "SSL Settings" for the site, make sure "Require SSL" is checked, and check the Client Certificates radio button for "Accept". Problem fixed!


The technique that worked for me in my case, after reading these answers to no avail, was simply to comment out all of my contract, and uncomment bits until it doesn't work anymore, in a binary search fashion. That narrows down the offending bit of code.

Then you just have to guess what's wrong with that code.

Some error feedback in the tool would have helped, of course.

I am writing a web service contract. I had a placeholder enum with no members. That's OK. But if I use it in a property of another class, and re-use the contract dll on the client, the codegen explodes with no error message. Running svcutil.exe didn't help, it just failed to output a cs file without mentioning why.


I also had the issue of broken service references when working with project references on both sides (the service project and the project having a reference to the service). If the the .dll of the referenced project for example is called "Contoso.Development.Common", but the projects name is simply shortened to "Common", also project references to this project are named just "Common". The service however expects a reference to "Contoso.Development.Common" for resolving classes (if this option is activated in the service reference options).

So with explorer I opened the folder of the project which is referencing the service and the "Common"-project. There I editet the VS project file (.csproj) with notepad. Search for the name of the refernced project (which is "Common.csproj" in this example) and you will quickly find the configuration entry representing the project reference.

I changed

<ProjectReference Include="..\Common\Common.csproj"> <Project>{C90AAD45-6857-4F83-BD1D-4772ED50D44C}</Project> <Name>Common</Name> </ProjectReference>

to

<ProjectReference Include="..\Common\Common.csproj"> <Project>{C90AAD45-6857-4F83-BD1D-4772ED50D44C}</Project> <Name>Contoso.Development.Common</Name> </ProjectReference>

The important thing is to change the name of the reference to the name of the dll the referenced project has as output.

Then switch back to VS. There you will be asked to reload the project since it has been modified outside of VS. Click the reload button.

After doing so adding und updating the service reference worked just as expected.

Hope this also helps someone else.

Regards MH


As @dblood points out, the main pain is in the DataContractSerializer, that doens't correctly re-use the types. There are already some answers here so I'll start by adding some pro's and cons about these:

  • The 'IsReference' flag causes a lot of trouble, but removing it isn't always the answer (specifically: in situations with recursion).
  • The underlying issue is that the data contract is somehow not the same as the type names, even though they sometimes are (huh? Yes, you read that right!). Apparently the serializer is quite picky and it's very hard to find the real issue.
  • Removing the 'references checks' from the 'Configure service reference' works, but leaves you with a multiple implementations. However, I often reuse SOAP interfaces across DLL's. Also, in most mature SOA's that I know, multiple services interfaces implement and extend the same interface classes. Removing 'use referenced types' checks results in a situation where you cannot simply pass objects around anymore.

Fortunately, if you are in control of your service, there is a simple solution that solves all these issues. This means you can still re-use service interfaces across DLL's - which is IMO a must-have for a proper solution. This is how the solution works:

  1. Create a separate interface DLL. In that DLL, include all DataContract and ServiceContract's; put ServiceContract's on your interfaces.
  2. Derive the server implementation from the interface.
  3. Use the same DLL to construct the client using your favorite method. For example (IMyInterface is the service contract interface):

    var httpBinding = new BasicHttpBinding();
    var identity = new DnsEndpointIdentity("");
    var address = new EndpointAddress(url, identity, new AddressHeaderCollection());
    var channel = new ChannelFactory<IMyInterface>(httpBinding, address);
    return channel.CreateChannel();
    

In other words: Don't use the 'add service reference' functionality, but force WCF to use the (correct) service types by bypassing the proxy generation. After all, you already have these classes.

Pro's:

  1. You bypass the svcutil.exe process, which means you don't have any IsReference issues
  2. DataContract types and names are correct by definition; after all, both server and client use the very same definition.
  3. If you extend the API or use types from another DLL, (1) and (2) still hold, so you won't run in any trouble there.

Cons:

  1. A-sync methods are a pain, since you don't generate an a-sync proxy. As a result, I wouldn't recommend doing this in Silverlight applications.

Thanks to John Saunders post above which gave me an idea to look into Error window. I was bagging all day my head and I was looking at Output window for any error.

In my case the culprit was ISerializable. I have a DataContract class with DataMember property of type Exception. You cannot have any DataMember of type which has ISerializable keyword. In this Exception has ISerializable as soon as I removed it everything worked like a charm.


If you recently added a collection to your project when this started to occur, the problem may be caused by two collections which have the same CollectionDataContract attribute:

[CollectionDataContract(Name="AItems", ItemName="A")]
public class CollectionA : List<A> { }

[CollectionDataContract(Name="AItems", ItemName="A")]  // Wrong
public class CollectionB : List<B> { }

I fixed the error by sweeping through my project and ensuring that every Name and ItemName attribute was unique:

[CollectionDataContract(Name="AItems", ItemName="A")]
public class CollectionA : List<A> { }

[CollectionDataContract(Name="BItems", ItemName="B")]  // Corrected
public class CollectionB : List<B> { }

Then I refreshed the service reference and everything worked again.


I had this problem with a Silverlight 5 upgraded from a previous version.

Even re-adding the service reference still gave me an empty Reference.cs

I ended up having to create a brand new project and re-creating the service reference. This is something to try if you've spent more than about half an hour on this. Even if you're determined to fix the original project you may want to try this just to see what happens and then work backwards to try to fix the problem.

I never did figure out exactly what the problem was - but possibly something in the .csproj file wasn't upgraded or some setting went wrong.


I have found this to occur commonly whenever I add a reference, remove it, and then re-add a service with the same name. The type conflicts appear to be caused by the old files remaining somewhere that Visual Studio can still see. All I need to do to fix it, is a clean before adding the new reference.

  1. Remove the service reference having issues.
  2. Click on the project name in the Solution Explorer to highlight the project.
  3. Right-click on the project reference.
  4. Near the top of the context list, click the Clean item.
  5. Add your service reference as you normally would.

Hope this helps.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to wcf

Create a asmx web service in C# using visual studio 2013 WCF Exception: Could not find a base address that matches scheme http for the endpoint WCF Service, the type provided as the service attribute values…could not be found WCF error - There was no endpoint listening at How can I pass a username/password in the header to a SOAP WCF Service The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM' Content Type application/soap+xml; charset=utf-8 was not supported by service The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) maxReceivedMessageSize and maxBufferSize in app.config how to generate a unique token which expires after 24 hours?