WCF with visual studio 2012 - c#

I am new WCF programming, I did followed series of Getting Started tutorials from following link
http://msdn.microsoft.com/en-us/library/ms734712.aspx
I have hosted service in console application but when I tried to create a client and tried to add service reference I got the following exceptions.
There was an error downloading
'http: localhost:8000/GettingStarted/mex/_vti_bin/ListData.svc/$metadata'.
The request failed with HTTP status 405: Method Not Allowed. Metadata
contains a reference that cannot be resolved:
'http: localhost:8000/GettingStarted/mex'. There was no endpoint
listening at http: localhost:8000/GettingStarted/mex that could
accept the message. This is often caused by an incorrect address or
SOAP action. See InnerException, if present, for more details. The
remote server returned an error: (404) Not Found. If the service is
defined in the current solution, try building the solution and adding
the service reference again.
code of hosting application
class Program
{
static void Main(string[] args)
{
// Step 1 Create a URI to serve as the base address.
Uri baseAddress =
new Uri("http://localhost:8000/GettingStarted/");
// Step 2 Create a ServiceHost instance
ServiceHost selfHost =
new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
// Step 3 Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
// Step 4 Enable metadata exchange.
var smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Step 5 Start the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("exception: {0}", ce.Message);
selfHost.Abort();
}
}
}
Now I am unable to figure out what the problem is. I am using visual studio 2012 and .net platform 4.5.

I had a similar issue as well, messing with this. Yes you seem to have followed the tutorial correctly, but if you want to connect to it and consume as a service (as in make a service reference) you must also add in the MEX service enpoint. Add this line after your selfhost.Description.Behaviors.Add(smb):
selfhost.AddServiceEndpoint(
typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexHttpBinding(),
"http://localhost:8000/GettingStarted/mex");
That should enable you to connect via "Add Service Reference". Also, I have found depending on your system, you may need to run VS as admin to allow for connection to network (in case you accidentally told it no in the past).

Judging from the error message it seems that there is no service listening at the specified port. You need to have the console application which hosts the service running when you are trying to add a service reference to it.

Apparently, the service is not running which means there is no endpoint listening at the URL you are using to create the service reference.
You can host the service in IIS, or keep the console application running as Damir mentioned above.

Make sure your server is running when you are trying to access it. Also check the configuration on the server and make sure your client's endpoint matches the server's endpoint. Make sure you're using the same binding as well, while you're at it.
Make sure the server is listening and the server's firewall isn't blocking you.
If you made a change to your WCF service don't forget to regenerate the service reference for your client application.

Are you sure you have defined a MEX endpoint? This is what provides metadata information about your service, so that studio can generate a client proxy.
In the tutorial you linked to, it is this bit:
// Step 4 Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);

If you are hosting the web service in IIS, check in web.config(under behaviours section)
httpsGetEnabled is set to True

I ran into a similar problem today. However, for me it wasn't needed for me to explicitly add the Endpoints, as #iMortalitySX already said.
I had a different reason for failing: I was binding to http://0.0.0.0, thinking the listen IP doesn't matter. Indeed, via SoapUI I was able to connect and to use the Service. But when trying to discover the service in another Visual Studio project, the discovery would fail, as VS would get the initial response, but then follow up links that contained http://0.0.0.0 and then fail.
So changing http://0.0.0.0 into the correct IP of my machine fixed my problem.

Try put the uri address in Your browser. In my case I was able to see an ExceptionDetail.

Related

'No connection could be made because the target machine actively refused it'

I am working on a 'Smart Device Project' using .Net Framework 3.5. I am trying to connect to some Java SOAP services on a remote server.
In order to do that, I added 'Web References' to my project.
When I try to call my web service I get a WebException 'Unable to connect to the remote server' with the inner exception being 'No connection could be made because the target machine actively refused it'.
I searched quite a lot on the Web and StackOverflow and found a lot of ASP configuration and 'Unavaliable port' answers, but as I have another application using the exact same Service successfully, I can't get why the new one isn't getting through (It did sometimes through my tests so I suppose my client implementation isn't that bad)
I tried to look if there was some connection issue on the port by using some TcpClient:
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
try
{
client.Connect("myServerName", 8087);
MessageBox.Show("Success");
} catch (Exception ex)
{
MessageBox.Show("Failure");
}
finally
{
client.Close();
}
This connection succeed.
Here is a sample on how I call my WebService:
WSServiceExtended srv = new WSServiceExtended();
srv.Proxy = new System.Net.WebProxy();
ServeurWSI wsi = new ServeurWSI();
srv.Url = "http://myServerName:8087/myServerApp/services/myService";
wsr = srv.login(wsi);
The service is called 'Extended' because I overrided the auto-generated one in order to add Cookie managment since I am using the Compact Framework. Following the sample in this thread:
https://social.msdn.microsoft.com/Forums/en-US/34d88228-0b68-4fda-a8cd-58efe6b47958/no-cookies-sessionstate-in-compact-framework?forum=vssmartdevicesvbcs
EDIT:
I made some new tests with the Web references and got it to work.
When I add the Web Reference, I have to put some Url to the Web Service. When I set it with the actual hostname instead of the 'localhost' everything is fine.
But then, since I set it manually to the real address just before the call, it shouldn't matter
srv.Url = "http://myServerName:8087/myServerApp/services/myService";
EDIT2:
I might have forgotten some specifics about my environnement.
The Web Services are exposed on my computer on some Tomcat Server.
The application I am working on is also developped on this computer (That's why I can add Web References by putting 'localhost' in the address)
The application is then deployed on a distant device (Windows CE) that will make calls the Web Services through WIFI (There, localhost wouldn't work then)
I tried calling the Web services from other computers successfully.
I'm beginning to think that there might be some differential between the called Url and the one that is set, otherwise, how would I have a difference in behaviour such as the one described in the first edit?
EDIT3:
Well..Seems like it's not a network issue but a .Net compact framework (usage?) issue...
The Url property of the Web Service implementation is simply ignored and the one in the Reference.cs is used in place.
If someone had some idea on how I could troubleshot this, I would really appreciate it.
That error means that you reached a server and the server said "no way". So you're either hitting the wrong server or the wrong port.
I find the telnet client is useful for testing stuff like this. From the command line, you can do:
telnet [servername] [port]
So something like:
telnet myServerName 8087
If it goes to a blank screen, then it connected successfully. If it does not connect, it'll tell you.
The telnet client is no longer installed by default in Windows 7+, so you'll have to install it. See here for instructions: https://technet.microsoft.com/en-ca/library/cc771275
If the connection does open, you could paste in an actual HTTP request to see what happens. A simple GET would look something like this:
GET /myServerApp/services/myService HTTP/1.1
Host: myServerName:8087
One reason for this error can be that the service binds to only a certain IP address. It could well be that the service only listens on the IP that is assigned to the host name, but not on the localhost IP (127.0.0.1).
For example:
If the host myServerName has the public IP 192.168.0.1, your service can choose to listen on all IPs assigned to the host (sometimes specifying 0.0.0.0), or it can specifically listen on 192.168.0.1 only. In that case you will not be able to connect through 127.0.0.1, because the service simply doesn't listen on that IP.
You can "use" this inverse of this feature to make a service accessible only to local clients, not on the public IP-Address, by listening on 127.0.0.1 only, but not on the public IP. This is sometimes used on Linux for example to make MySQL only accessible on the host itself.
I was starting to forget this post but I finally found the problem that was messing things up and it has nothing to do with programmation.
I was doing the calls while the device was connected to the computer via the 'Windows Mobile Device Center' allowing to access the device from Windows.
While connected, the host provided is ignored and all calls on the specified port are handled by the connected computer.
Disconnecting the device allows to communicate properly...

Silverlight client consuming WCF service

Please bear with me as I am new to WCF services/ Windows services. I've created a WCF service hosted in a Windows service. I want to consume that WCF service in a Silverlight in-browser application over TCP. Below is the code fragment in Silverlight to access WCF service:
var messageEncoding = new BinaryMessageEncodingBindingElement();
var tcpTransport = new TcpTransportBindingElement();
var binding = new CustomBinding(messageEncoding, tcpTransport);
// Create a channel factory for the service endpoint configured with the custom binding.
var cf = new ChannelFactory<ICalcService>(binding, new EndpointAddress("net.tcp://192.168.2.104:4508"));
// Open the channel.
ICalcService channel = cf.CreateChannel();
// Invoke the method asynchronously.
channel.BeginAdd(9, 5, AddCallback, channel);
private void AddCallback(IAsyncResult asyncResult)
{
try
{
double endAdd = ((ICalcService) asyncResult.AsyncState).EndAdd(asyncResult);
}
catch (Exception exception)
{
throw exception;
}
}
The code works fine sometimes but often it throws an infamous System.ServiceModel.CommunicationException with the following message for some reasons:
Could not connect to net.tcp://192.168.2.104:4508/. The connection attempt lasted for a time span of 00:00:00.1010058. TCP error code 10013: An attempt was made to access a socket in a way forbidden by its access permissions.. This could be due to attempting to access a service in a cross-domain way while the service is not configured for cross-domain access. You may need to contact the owner of the service to expose a sockets cross-domain policy over HTTP and host the service in the allowed sockets port range 4502-4534.
The innerException of type System.Net.Sockets.SocketException says
An attempt was made to access a socket in a way forbidden by its access permissions.
What are the possible reasons behind this exceptions? Based on what I investigated so far, I could find only one reason: Improper ClientAccessPolicy.xml. What may be the other reasons? If you have any useful resources, please provide me the same. One more question, if I want to make Windows service hosted WCF service to get consumed by other machines on LAN, what settings do I have to make? E.g. firewall settings? My code cannot access WCF service on other machine. It throws the same exception I mentioned above. Any ideas about how to get rid of this exception?
Problem sorted..!! I had to do following things:
1) Specified SecurityMode.None while creating NetTcpBinding in Windows service.
2) Created an Inbound Rule in Windows Firewall With Advanced Security to allow TCP traffic on the port I specified in the end point address.

How to use NetTcpBinding in code?

Not a duplicate! - The suggested duplicate deals with one using netTcpBinding and one using mexTcpBinding. Read on to see that that is not the case here:
Here's my code:
ServiceHost host = new ServiceHost(class1Type, new Uri(uri));
host.AddServiceEndpoint(interface1Type, new NetTcpBinding(SecurityMode.None), uri);
host.Open();
I have made a copy of the project and am running two instances with one difference - the last character in the uri string. There is nothing in the configuration file. All is in code.
The uri is of the form:
net.tcp://localhost/abc/def
I'm getting an error:
There is already a listener on IP endpoint 0.0.0.0:808. This could
happen if there is another application already listening on this
endpoint or if you have multiple service endpoints in your service
host with the same IP endpoint but with incompatible binding
configurations.
I don’t understand this error, both services are the same, so how can they be incompatible?
All I was missing was:
PortSharingEnabled = true
(I don't think the error message is clear enough.)

net.tcp no longer works in server 2012

I cannot get server 2012 iis to host net.tcp.
In server 2008R2/VS2012 there is no issues
In server2012/VS2012 when hitting the wdsl I am first receiving "The protocol 'net.tcp' does not have an implementation of HostedTransportConfiguration type registered.", then if I hit refresh I get "An item with the same key has already been added."
The error from the TraceViewer if "service is unable to open its IChannelListener"
But I have set the Bindings on the default website( had to use the command line because it throws an exception if you edit net.tcp in the grid, this is a known issue)
I have set the bindings at the application level to http,net.tcp, created a new AppPool with network service identity, and used findPrivateKey to give it permissions.
I created a new virt of Server 2008R2/VS2012 and had no issues with the above steps.
Edit Additional notes for server 2012
Add Roles and Features:
Verified the following are installed:
Web Sever - Application Development: All checked but CGI and ASP(classic)
.NET Framework 3.5 Features: All checked
Windows Process Activation Service: All checked
IIS: Default Web Site: bindings net.tcp 8081:
IIS: Default Web Site->Advanced Settings->enabled protocols: http,net.tcp
IIS: Default Web Site\Service->Advanced Settings->enabled protocols: http,net.tcp
Is there anything special to do for Server2012?
After a day of searching, finally found it. I guess it another known issue with server2012 & IIS8
http://support.microsoft.com/kb/2803161
Here some tips that you could try:
1-Open a Command Prompt (as administrator) and run:
netstat -ona
Check if your service is listening to your server port.
Example: your endpoint is net.tcp://localhost:8015/MyService. So running the command above, you will see an item:
TCP 127.0.0.1:8015 0.0.0.0 LISTENING
2-If your service is not listening, then create a Console app and self-host your service.
Example:
using System.ServiceModel.ServiceHost;
public class Sample
{
ServiceHost host = new ServiceHost(typeof(MyService));
public static void Main()
{
host.Open();
Console.WriteLine("listening...");
Console.Read();
host.Close();
}
}
3-Repeat the first step and check if your service is listening to the port.

WCF error "no endpoint listening" with named pipes

I'm using WCF with .NET 3.5 I am using named pipes but keep getting the error
There was no endpoint listening at
net.pipe://localhost/Test that could
accept the message. This is often
caused by an incorrect address or SOAP
action.
I followed the tutorial http://www.switchonthecode.com/tutorials/wcf-tutorial-basic-interprocess-communication but the problem remains. The endpoints on both the client and server are the same (I checked spelling etc). There is no config file for this project but the config is in the code.
EDIT: Code (client):
ChannelFactory<ITest> pipeFactory =
new ChannelFactory<ITest>(
new NetNamedPipeBinding(),
new EndpointAddress(
"net.pipe://localhost/test"));
ITest test= pipeFactory.CreateChannel();
test.doStuff();
SERVER:
serviceHost = new ServiceHost(typeof(Test), new Uri("net.pipe://localhost"));
serviceHost.AddServiceEndpoint(typeof(ITest), new NetNamedPipeBinding(), "test");
File.Create(#"C:\test.txt");
serviceHost.Open();
Thanks
On the server side don't include base addresses when you create the ServiceHost instance. Instead, provide the fully qualified endpoint address when you add the service endpoint:
serviceHost = new ServiceHost(typeof(Test));
serviceHost.AddServiceEndpoint(typeof(ITest), new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/test"));
File.Create(#"C:\\test.txt");
serviceHost.Open();
This could be:
You are running it as a windows service and the service is not running
You are running it as a console app and there is no console.readline, so it just exists
You are running client and server on two different machines so that localhost is not going to the machine with the service.
Another possibility to fix this root issue if you are getting an error that no net.pipe address can be found at your url (i.e. http://localhost:1234/MyService/etc/) is to make sure that the Net.Pipe Listener Adapter Windows Service is started. (I also started Net.Tcp Listener Adapter)
The service does not seem to be enabled or started in some scenarios especially when deploying out to a remote server that might not of had a lot of the development tools installed that actively use these services. Starting the service fixed the issue.

Categories