connect programmatically to a WCF service through HTTPS - wcf

I am working on a project that uses WCF service. I have built the service, configured the web.config file, deployed it on a IIS 7 server. The service is accesed through HTTPS (on my dev machine, i have self-created the certificate).
Everything is fine when a create the ServiceReference in Visual Studio 2010, it creates the client and it works fine.
What i need is to create a client programatically (need a little flexibility), so when i try to connect "manually", it gives me a error like this:
The provided URI scheme 'https' is invalid; expected 'http'.
Parameter name: via
The code for web.config is: (i hope there is nothing wrong in it)
<system.serviceModel>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="TransportSecurity" contract="WcfService1.IService1" />
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfService1.Service1Behavior">
<serviceMetadata httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="TransportSecurity">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
The procedure i wrote to access the WCF service is:
void proc()
{
string ADRESASSL = "https://localhost/ServiciuSSLwsBind/Service1.svc";
WSHttpBinding bind= new WSHttpBinding();
EndpointAddress ea = new EndpointAddress(ADRESASSL);
var myChannelFactory = new ChannelFactory<IService1>(bind, ea);
IService1 client = null;
try
{
client = myChannelFactory.CreateChannel();
client.RunMethod1();
client.Close();
//((ICommunicationObject)client).Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
if (client != null)
client.Close();
}
}
The code for IService1
[ServiceContract]
public interface IService1 : IClientChannel
{
[OperationContract]
int RunMethod1();
//....................................
}
It seems i am doing something wrong here, the procedure raises the Exception i mentioned. Something more i must do to work, but i didn't figured it out.
Thanks in advance for any advice you can give me.

I haven't tested this, but I believe you need to set the security mode for the binding before you create the factory. The default mode for security for WSHttpBinding is SecurityMode.Message, and you want SecurityMode.Transport.
You can resolve this one of three ways, as follows.
First, you can use the overloaded version of the WSHttpBinding constructor to specify the security mode, like this:
WSHttpBinding bind= new WSHttpBinding(SecurityMode.Transport);
bind.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
Secondly, you can use the parameterless constructor and specify the security mode (and the client credential type) like this:
WSHttpBinding bind= new WSHttpBinding();
bind.Security.Mode = SecurityMode.Transport;
bind.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
Third, you can place a binding configuration section in the client config and reference that section in the constructor, like this:
WSHttpBinding bind = new WSHttpBinding("TransportSecurity");
The third example assumes a wsHttpBinding section with the name "TransportSecurity" in the client config file.
For more information, check these MSDN articles:
How to: Set the Security Mode
WSHttpBinding Constructor

Well, solved the problem with the self created certificate.
I have changed the endpoint adress for both the programatically connection and the service reference in Viosual Studio 2010.
string ADRESASSL = "https://localhost/ServiciuSSLwsBind/Service1.svc";
now is
string ADRESASSL = "https://eu-pc/ServiciuSSLwsBind/Service1.svc";
I have changed the adress from localhost to the name of pc "eu-pc". It has to do with the domain the certificate was issued.
Using localhost or 127.0.0.1 worked only for one method or the other.
Hope this will help other guys who might run into this.

Related

Client Certs for WCF consumer stops working after a while

I am having really peculiar issue with certs not working after a while for WCF Client App that connect to SOAP 1.1 SAP service. What boggles me is the steps I have to take to make the certs work again. After I installed the certs on couple of load balanced servers, seems like everything works fine. But then after a few days, one of the app/servers throws this error.
The request was aborted: Could not create SSL/TLS secure channel.
When I log on to the server using MMC and open the cert (I do not even have to reinstall it, just open is good enough), the web app works. I am at my wits end as to why this might be happening. Any help will be appreciated.
Below are the architecture/some code samples of how the apps/web services are set up
[MVC WebApp]--[ Load Balancer ]-->(Server 1, Server 2)--> SAP SOAP 1.0 Web Service
Some configuration and code samples..
<system.serviceModel>
<client>
<endpoint address="https://somesapwebservice:8104/XISOAPAdapter/MessageServlet?senderParty=&senderService=BC_PORTAL&receiverParty=&receiverService=&interface=SI_AppFormData_Out_Sync&interfaceNamespace=urn%3Acominc.com%3AOTC%3AI1053%3AppForm" behaviorConfiguration="secureCert" binding="wsHttpBinding" contract="somecontract_Out_Sync" name="HTTPS_Port" />
</client>
<bindings>
<wsHttpBinding>
<binding>
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="secureCert">
<clientCredentials>
<clientCertificate storeName="My" storeLocation="CurrentUser" x509FindType="FindBySubjectDistinguishedName" findValue="CN=CNN, OU=Windows, OU=SAP, OU=Service Accounts, OU=Admin, OU=CORP, DC=myinc, DC=ds" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
..
<appSettings>
<add key="ProtocolExceptionMessage" value="The content type text/xml; charset=utf-8 of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8)" />
C# Code
public ActionResult FormSubmit(SubmitViewModel model)
try
{
this.SubmitToSAPService(model);
return this.RedirectToAction("Index", "Complete");
}
catch (ProtocolException pe)
{
// Current SAP only support SOAP 1.1 and WCF with .NET 4.6 runs on SOAP 1.2 - Catching the known exception
// Creating custom WCF binding to handle this is another possibility but that config could get convoluted
var messageSnippet = ConfigurationManager.AppSettings["ProtocolExceptionMessage"];
if (pe.Message.Contains(messageSnippet))
{
return this.RedirectToAction("Index", "Complete");
}
throw pe;
}
One thing I am doing little off here is that I was told is that SAP is currently running SAOP 1.1 and .NET we are running is SOAP 1.2. So I was always getting Protocol Exception. To get around that I check for the text and if the exception message matches exactly as expected, I bypass it.
public string SubmitToSAPService(SubmitViewModel model)
{
var dtFormDataRecords = new DT_FormData();
dtFormDataRecords.Records = new DT_FormDataRecords();
dtFormDataRecords.Records.Name = model.name
....
var client = new SI_AppFormData_Out_SyncClient();
try
{
client.SI_AppFormData_Out_Sync(dtFormDataRecords);
}
finally
{
client.Close();
}
...
After trying to run intellitrace on the app, that let to clue me in the app-pool settings Load User Profile was set to False. That had cause the issue I was getting. After I set the it to True, my issue was resolved.

WCF inter-service messaging

I am building a system with 2 WCF Services. Both are IIS Hosted. At the moment they both reside in a single VS2010 website app, running on my local IIS7 (Windows 7) using the Derfault Website. I have enabled net.tcp on both.
Service1
accepts HTTP posts using webHttpBinding
wraps the data in a serializable composite object
sends the composite object to Service2 (we hope) using netMsmqBinding
Service2
receives said message and does something with it
Service 1 works as expected, however instead of placing the message on the configured Private Queue, our code is creating a new Queue under "Outgoing Queues" with the handle
DIRECT=TCP:127.0.0.1\private$\Service2/Service2.svc
note the forward slash
Of course Service2 never sees the message - this is the first time I have attempted this structure so I am not certain that Service2 misses the message because of its location, but based on what I have read it would seem so - I have not come across anything mentioning this Queue-creation behaviour.
Questions:
Am I doing this correctly (is there something wrong in the structure, web.config or code)?
When done properly in VS Debug, should Service1's
proxy.ProcessForm(formMessage);
hit breakpoints in my Service2 code, or is there another way to hande Service2 debug (ala windows services for example)?
Service1 Web.Config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpFormBinding" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
<netMsmqBinding>
<binding name="MsmqFormMessageBindingClient" exactlyOnce="false" useActiveDirectory="false" >
<security mode="None">
<message clientCredentialType="None"/>
<transport msmqAuthenticationMode="None" msmqProtectionLevel="None" />
</security>
</binding>
</netMsmqBinding>
</bindings>
<client>
<endpoint
name="HttpServiceWebEndpoint"
address=""
binding="webHttpBinding"
bindingConfiguration="webHttpFormBinding"
contract="Service1.HttpService.IHttpServiceWeb" />
<endpoint name="MsmqFormMessageBindingClient"
address="net.msmq://127.0.0.1/private/Service2/Service2.svc"
binding="netMsmqBinding"
contract="MyInfrastructure.IService2" />
</client>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
<!--
<serviceAuthenticationManager />
-->
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
On Receipt of an HTTP Post Service1 executes the following:
StreamReader sr = new StreamReader(formData);
string str = sr.ReadToEnd();
var t = HttpUtility.ParseQueryString(str);
Hashtable nvc = new Hashtable();
foreach (string n in t)
{
nvc.Add(n, (string)t[n]);
}
WcfFormMessage formMessage = new WcfFormMessage(nvc);
////create the Service binding
NetMsmqBinding msmq = new NetMsmqBinding("MsmqFormMessageBindingClient");
msmq.Security.Mode = (NetMsmqSecurityMode) MsmqAuthenticationMode.None;
EndpointAddress address = new EndpointAddress("net.msmq://127.0.0.1/private/Service2/Service2.svc");
ChannelFactory<IService2> factory = new ChannelFactory<IFormService>(msmq,address);
IService2 proxy = factory.CreateChannel();
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
proxy.ProcessForm(formMessage);
//do any 'sent to queue logging/updates here
}
I am ready to bet that your problem is related to 127.0.0.1 in your config. Type the machine name in there, even if it is local.

Setting binding in WCF service

This may seem like a really easy question but I can't seem to figure it out at all.
I'm trying to create a new WCF service, and I'm new to having to secure them. I'm using a custom username/password for authentication. The problem [right now anyways] that I seem to be running into is that I can't figure out how to define the service to use the WSHttpBinding (on the service side, not the client side).
Am I missing something incredibly simple? Any pointers and/or recommendations would be greatly appreciated!
EDIT
Here's my code so far:
IAccountService
[ServiceContract]
public interface IAccountService
{
[OperationContract]
bool IsCardValid(string cardNumber);
[OperationContract]
bool IsAccountActive(string cardNumber);
[OperationContract]
int GetPointBalance(string cardNumber);
}
Service web.config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
<StructureMapServiceBehavior />
</behavior>
</serviceBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="StructureMapServiceBehavior" type="Marcus.Loyalty.WebServices.Setup.StructureMapServiceBehavior, Marcus.Loyalty.WebServices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<services>
<service name="Marcus.Loyalty.WebServices.Account.IAccountService">
<endpoint address=""
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_Config"
contract="Marcus.Loyalty.WebServices.Account.IAccountService"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_Config"/>
</wsHttpBinding>
</bindings>
</system.serviceModel>
Testing app (console app)
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter card number");
var number = Console.ReadLine();
var endPoint = new EndpointAddress("http://localhost:59492/Account/AccountService.svc");
var binding = new WSHttpBinding(SecurityMode.Message);
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
var cf = new ChannelFactory<IAccountService>(binding, endPoint);
cf.Credentials.UserName.UserName = "testuser";
cf.Credentials.UserName.Password = "Password1!";
var service = cf.CreateChannel();
var balance = service.IsAccountActive(number);
Console.WriteLine("\nBALANCE: {0:#,#}", balance);
Console.Write("\n\nPress Enter to continue");
Console.Read();
}
}
Testing app app.config
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="BasicHttpBinding_IAccountService" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:59492/Account/AccountService.svc"
binding="wsHttpBinding" bindingConfiguration="BasicHttpBinding_IAccountService"
contract="ServiceReference1.IAccountService" name="BasicHttpBinding_IAccountService" />
</client>
</system.serviceModel>
</configuration>
You need to define the abc (address, binding, contract) configuration into de web.config file (you can also do it programmatically. the b part, the binding, you can specify the wsHttpBinding
<system.serviceModel>
<services>
<service name = "MyNamespace.MyService">
<endpoint
address = "http://localhost:8000/MyService"
binding = "wsHttpBinding"
contract = "MyNamespace.IMyContract" />
</service>
</services>
</system.serviceModel>
If you wish to enable security in a proper way, there is a lot of literature and options. You can use certificates, windows based, tokens, ... passing a username & password like a parameter could not be the best way to do it.
There is an extensive sample on MSDN (How to: Specify a Service Binding in code) - but basically, you need to have:
your service contract (IMyService)
an implementation of that service (MyService)
a code where you create your ServiceHost to host your service
You got all of that? Great!
In that case, just do something like this:
// Specify a base address for the service
string baseAddress = "http://YourServer/MyService";
// Create the binding to be used by the service.
WsHttpBinding binding1 = new WsHttpBinding();
using(ServiceHost host = new ServiceHost(typeof(MyService)))
{
host.AddServiceEndpoint(typeof(IMyService), binding1, baseAddress);
host.Open();
Console.ReadLine();
}
and now you should have your service host up and running, on your chosen base address and with the wsHttpBinding defined in code.

WCF, MVC2, obtaining access to auto generated WSDL and working through default endpoint not found issues

I’m trying to run a very basic web service on the same IIS7 website that runs a MVC2 application. This is presenting a couple of different issues, and I believe it has to do with my system.serviceModel, but obviously I don’t know for sure (or I would fix it).
On the server side I can run my service just fine, the help operation works like a charm. I can execute the default WCF operation GetData and supply a value through the FireFox address bar.
http://localhost/services/service1/getdata?value=3 (example)
The first problem I’m having is that when I navigate to the base service URI it will display the message below. While this isn’t the end of the world because I can still execute code by manipulating the address; I do expect something else to be displayed. I expect the standard new web service message explaining that by appending “?wsdl” to the address you will receive the auto generated WSDL. I cannot access my auto generated WSDL.
“Endpoint not found. Please see the
service help page for constructing
valid requests to the service.”
Problem number two is in regard to client applications connecting to my web service. I created a console application in separate Visual Studio solution and added a web service reference to Service1. In the Visual Studio tool I can see and use the two methods that exist in my service, but when I run the code I get the following exception.
InvalidOperationException Could not
find default endpoint element that
references contract
'ServiceReference1.IService1' in the
ServiceModel client configuration
section. This might be because no
configuration file was found for your
application, or because no endpoint
element matching this contract could
be found in the client element.
Before I post my code (I’m sure readers are tired of reading about my struggles) I do want to mention that I’ve been able to run a WCF Service Library and Console application in the same solution flawlessly. There seems to be very few resources explaining WCF, WCF configuration, and working with MVC. I’ve read through several articles and either they were out-of-date or they were so simplistic they were nearly useless (e.g. click button receive web service named “Service1”).
To summarize; why am I not able to access the auto generated WSDL and how can I successfully connect my client and use the web service? Now the best part; the code.
Global.asax
//Services section
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
Web.Config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="DefaultEndpoint" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
<mexEndpoint />
</standardEndpoints>
<services>
<service name="Project.Services.Service1" behaviorConfiguration="MetadataBehavior">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MetadataBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false" /> <!-- httpGetEnabled="true" does not solve the problem either -->
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET")]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
Service1
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
Client Program
class Program
{
static void Main(string[] args) {
Service1Client client = new Service1Client();
client.GetData(2);
}
}
Thanks for the help! The problem was inside of my Global.asax.cs.
Original:
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
New:
routes.Add(new ServiceRoute("services/service1", new ServiceHostFactory(), typeof(Service1)));
The difference was chaing the host factory from "WebServiceHostFactory" to "ServiceHostFactory".
The second part of my question regarding client connections is because configuration settings are not being generated. I have to manually type them for each client. Yikes!
To avoid manually typing client configuration I had to change my endpoint
Original
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
New
<endpoint binding="wsHttpBinding" contract="Project.Services.IService1" />
After making this change the service and client are working flawlessly.
A quick answer to one of your questions:
To summarize; why am I not able to
access the auto generated WSDL
<serviceMetadata httpGetEnabled="false" />
...needs to be
<serviceMetadata httpGetEnabled="true" />
...in order to be able to retrieve the WSDL over http. You have to tell WCF to generate service metadata, and you've told it not to.

WCF Metadata contains a reference that cannot be resolved

I've spent a couple of hours searching about this error, and I have tested almost everything it's on Google.
I want to access a service using TCP, .NET4 and VS2010, in C#.
I Have a very tiny service:
namespace WcfService_using_callbacks_via_tcp
{
[ServiceContract(CallbackContract = typeof(ICallback), SessionMode = SessionMode.Required)]
public interface IService1
{
[OperationContract]
string Test(int value);
}
public interface ICallback
{
[OperationContract(IsOneWay = true)]
void ServerToClient(string sms);
}
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : IService1
{
public string Test(int value)
{
ICallback the_callback = OperationContext.Current.GetCallbackChannel<ICallback>();
the_callback.ServerToClient("Callback from server, waiting 1s to return value.");
Thread.Sleep(1000);
return string.Format("You entered: {0}", value);
}
}
}
With this Web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfService_using_callbacks_via_tcp.Service1" behaviorConfiguration="Behaviour_Service1">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:5050/Service1" />
</baseAddresses>
</host>
<endpoint address="" binding="netTcpBinding" bindingConfiguration="DuplexNetTcpBinding_IService1" contract="WcfService_using_callbacks_via_tcp.IService1"/>
<endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="mexTcp" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<!--
TCP Binding
-->
<netTcpBinding>
<binding name="DuplexNetTcpBinding_IService1" sendTimeout="00:00:01"
portSharingEnabled="true">
</binding>
<binding name="mexTcp" portSharingEnabled="true">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<!--
Behaviour to avoid a rush of clients and to expose metadata over tcp
-->
<behavior name="Behaviour_Service1">
<serviceThrottling maxConcurrentSessions="10000"/>
<serviceMetadata httpGetEnabled="true"/>
</behavior>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
And this code to host it:
static void Main(string[] args)
{
Uri base_address = new Uri("net.tcp://localhost:5050/Service1");
ServiceHost host = null;
try
{
// Create the server
host = new ServiceHost(typeof(Service1), base_address);
// Start the server
host.Open();
// Notify it
Console.WriteLine("The service is ready at {0}", base_address);
// Allow close the server
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close it
host.Close();
}
catch (Exception ex)
{
// Opus an error occurred
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Format("Host error:\r\n{0}:\r\n{1}", ex.GetType(), ex.Message));
Console.ReadLine();
}finally
{
// Correct memory clean
if(host != null)
((IDisposable)host).Dispose();
}
}
Now I want to create the client, but I it is not posible. I've used Add Service Reference and svcutil directly, but I am receiving this error:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>svcutil.exe
net.tcp://loc alhost:5050/Service1 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
'net.tcp://localhost:5050/Service1' using W S-Metadata Exchange. This
URL does not support DISCO. Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version
4.0.30319.1] Copyright (c) Microsoft Corporation. All rights reserved.
Error: Cannot obtain Metadata from net.tcp://localhost:5050/Service1
If this is a Windows (R) Communication Foundation service to which you
have acce ss, please check that you have enabled metadata publishing
at the specified addr ess. For help enabling metadata publishing,
please refer to the MSDN documentat ion at
http://go.microsoft.com/fwlink/?LinkId=65455.
WS-Metadata Exchange Error
URI: net.tcp://localhost:5050/Service1
Metadata contains a reference that cannot be resolved: 'net.tcp://localhost: 5050/Service1'.
The socket connection was aborted. This could be caused by an error processi ng your message or a receive timeout being exceeded by
the remote host, or an un derlying network resource issue. Local
socket timeout was '00:04:59.9863281'.
Se ha forzado la interrupción de una conexión existente por el host remoto
If you would like more help, type "svcutil /?"
So, I can host the service without problems but I can not create the proxies.
I've tried almost any config I've found, but I think the current web.config is correct. There are the behaviours, the security, and the bindings using mex, used by the endpoints.
I've tried to create an app.config and set it to the same folder with svcutil.exe.
You are missing service configuration
<system.serviceModel>
<services>
<service name="WcfService_using_callbacks_via_tcp.Service1"
behaviorConfiguration="Behavior_Service1">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:5050/Service1" />
</baseAddresses>
</host>
<endpoint address="" contract="WcfService_using_callbacks_via_tcp.IService1"
binding="netTcpBinding" bindingConfiguration="DuplexNetTcpBinding_IService1" />
<endpoint address="mex" contract="IMetadataExchange" binding="mexTcpBindng" />
</service>
</services>
...
</system.serviceModel>
With this config you should not need to define base address in code.
I received the same error while attempting to update an existing service reference. It turns out I had data contracts with the same name within the same namespace. Further investigation yielded the real error:
DataContract for type [redacted] cannot be added to DataContractSet since type '[redacted]' with the same data contract name 'DocumentInfo' in namespace '[redacted]' is already present and the contracts are not equivalent.
I changed the DataContract to provide a name for one of the classes.
[DataContract(Namespace = "urn:*[redacted]*:DataContracts", Name = "SC_DocumentInfo")]
I'm posting this here in case it might help someone with the same issue.
I was getting the same error message and as it turned out, the issue was due to text within a comments block
<!-- comments included characters like à, ç and ã -->
After removing such characters from the commented block, everything works fine
Maybe it will be helpful for someone.
My issue was in a contract argument, and I discovered it with help of Event Viewer:
The operation [Name of method] either has a parameter or a return type that is attributed with MessageContractAttribute. In order to represent the request message using a Message Contract, the operation must have a single parameter attributed with MessageContractAttribute. In order to represent the response message using a Message Contract, the operation's return value must be a type that is attributed with MessageContractAttribute and the operation may not have any out or ref parameters.
So, if you appended more than one arguments, already having [MessageContract] argument, then you'll see error in question. Completely not obvious.
I had the same problem (when client didn't "see" the service in "Add service reference" menu) while using only tcp binding. After trying to add Behavior I had my service to end with exception because it didn't find proper address.
I don't know if it is the best idea, but you can add second base address as http.... here is my config and code, it works.
<?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <services>
<service name="TestBindings.StockQuoteService">
<host>
<baseAddresses>
<add baseAddress="net.tcp://10.62.60.62:34000/StockQuoteService" />
<add baseAddress ="http://10.62.60.62:12000/StockQuoteService"/>
</baseAddresses>
</host>
<endpoint address=""
contract="TestBindings.IStockQuoteService"
binding="netTcpBinding" />
</service>
</services>
And the code
class Program
{
static void Main(string[] args)
{
ServiceHost sh = new ServiceHost(typeof(StockQuoteService));
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
sh.Description.Behaviors.Add(behavior);
sh.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(),
"mex");
sh.Open();
The http address is now usend by client to add service reference, and automatically generated config on client side uses net.tcp protocol to call the function.
There is yet another reason to run into this one. Similar to the DataContract related answer here, WCF services also don't support method overloading in operation contracts. It'll raise this confusing catch-all exception as well.
The fix is simple enough:
[OperationContract]
T[] Query(int id);
[OperationContract(Name = "QueryWithArg")]
T[] Query(int id, string arg);
For the above issue check the reference.svc file which is generated at the time you add the reference. The url mentioned in that will be used for updating the service so you can check whether that is running or not.