WCF EndpointNotFoundException - wcf

I am working on a simple WCF service, MiniCalcService which has only one operation Add. The client and host are both console applications. The client application takes in the operands necessary for each operation and passes them over to the service. The service returns the result which would be displayed on the client console.
Host is running
I am doing everything in code so far and there is no app.config.
There is no large data being passed, just two or three numbers
This worked for me yesterday. Today when I tried the same thing, it throws the following exception:
There was no endpoint listening at http://localhost:8091/MiniCalcService that could accept the message.
Here is the Stack Trace. Not that it might matter, but MiniCalcClient is developed in Visual Studio and MiniCalcService and MiniCalcHost are developed in SharpDevelop.
MiniCalcHost:
using(ServiceHost host = new ServiceHost(typeof(MiniCalcService.Service), new Uri("http://localhost:8091/MiniCalcService")))
{
host.AddServiceEndpoint(typeof(MiniCalcService.IService),new BasicHttpBinding(),"Service");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("Serving MiniCalcService since {0}", DateTime.Now);
Console.Write("Press ENTER key to terminate the MiniCalcHost . . . ");
Console.ReadKey(true);
}
MiniCalcClient:
static string Calculator(string operation, params string[] strOperands)
{
EndpointAddress ep = new EndpointAddress("http://localhost:8091/MiniCalcService");
IService proxy = ChannelFactory<IService>.CreateChannel(new BasicHttpBinding(), ep);
int[] operands;
string result = string.Empty;
try { operands = Array.ConvertAll(strOperands, int.Parse); }
catch (ArgumentException) { throw; }
switch (operation)
{
case "add":
result = Convert.ToString(proxy.Add(operands));//<---EXCEPTION
break;
default:
Console.WriteLine("Why was this reachable again?");
break;
}
return result;
}
Service Contract IService:
[ServiceContract(Namespace="learning.wcf.MiniCalc")]
public interface IService
{
[OperationContract]
double Add(params int[] operands);
}
Can you please help me identify what's causing this exception?
Solution: I changed this line:
EndpointAddress ep = new EndpointAddress("http://localhost:8091/MiniCalcService");
to this:
EndpointAddress ep = new EndpointAddress("http://localhost:8091/MiniCalcService/Service");
and it worked.

I'm not sure if you can use the params in a WCF service call.... seems unnecessary, anyway....
Could you try these two service contracts instead, just to see if those would work:
[ServiceContract(Namespace="learning.wcf.MiniCalc")]
public interface IService2
{
[OperationContract]
int Add(int op1, int op2);
}
and
[ServiceContract(Namespace="learning.wcf.MiniCalc")]
public interface IService3
{
[OperationContract]
int Add(List<int> operands);
}
I'm just wondering if removing the params from your service contract might make it run - everything seems fine at first glance...
OK, so it wasn't this first attempt ......
Well - quite obvious, really: you're using a using block around the service host instantiation:
using(ServiceHost host = new ServiceHost(typeof(MiniCalcService.Service), new Uri("http://localhost:8091/MiniCalcService")))
{
host.AddServiceEndpoint(typeof(MiniCalcService.IService),new BasicHttpBinding(),"Service");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("Serving MiniCalcService since {0}", DateTime.Now);
Console.Write("Press ENTER key to terminate the MiniCalcHost . . . ");
}
So by the time the code reaches the closing bracket }, the ServiceHost instance will be disposed and thus the service host closed. There's no running service host anymore!
You need to stop the code execution somewhere after the call to host.Open() by e.g.
Console.ReadLine();
or something else.
So your first claim that Host is running really doesn't hold up - it's running briefly and then is terminated again right away.....

Related

How to get the WCF service address from DynamicEndpoint

I Crreated a DynamicEndpoint to find the WCF service automatically.
namespace Client
{
class Program
{
static void Main(string[] args)
{
DynamicEndpoint dynamicEndpoint = new DynamicEndpoint(ContractDescription.GetContract(typeof(ICalculator)), new NetTcpBinding());
using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(dynamicEndpoint))
{
ICalculator caculate = channelFactory.CreateChannel();
Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 4, 9, caculate.Add(4, 9));
Console.WriteLine("Find service, the service address is: " + dynamicEndpoint.Address.Uri);
}
Console.Read();
}
}
}
The problem is when I try to print the service address, the return value is
http://schemas.microsoft.com/discovery/dynamic
That's not the real service address I published.
1. How to get the real service address?
2. If there are multiple services available, which one will DynamicEndpoint choose? Can I get the address array or list?
As far as I know, we could not get the actual use endpoint in client. except that we use the OperationContext object,which provides access to the execution context of a service method.
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.operationcontext?redirectedfrom=MSDN&view=netframework-4.7.2
For example, we could refer to the following code to get the actual endpoint.
Server.
public string GetAddress()
{
OperationContext oc = OperationContext.Current;
string result=oc.Channel.LocalAddress.Uri.ToString();
return result;
}
Client.
ChannelFactory<IService> factory = new ChannelFactory<IService>(dynamicEndpoint);
IService sv = factory.CreateChannel();
Console.WriteLine(sv.GetAddress());
Besides,I don't think dynamic endpoint could list the endpoints that have been found. Dynamic Endpoint merge service discovery with service invokation. when a service is invoked using a dynamic endpoint, it will depend on the FindCriteria property to find the service endpoint and then invokes it.
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.discovery.dynamicendpoint?view=netframework-4.7.2
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.discovery.findcriteria?view=netframework-4.7.2

Using an existing WCF service

I am very new at programming WCF services, so I hope that if you answer my question - you will take that into account and explain it to me as if I was a kid (wcf services for dummies :). I have an existing WCF service which I need to connect to. I am supposed to make my own WCF service that will communicate with the existing one and share some request and response objects which are already defined in the existing service. Can anyone tell me how to do that (establish the communication between the two and use the same type of object in the service which I need to make as it is in the existing one), step by step? I have tried to find the answer online but it is all a bit confusing (referencing, using contracts...). As I said, you are free to explain as if you would to a real beginner. Any help is more than welcome...
"I am supposed to make my own WCF service that will communicate with the existing one and share some request and response objects which are already defined in the existing service." - This sounds like you need to create a client to connect to the service (see below how to create client). You can create WCF service to communicate with another service but you would need bit more background than this format allows.
You can get up to speed with WCF through WCF examples. Under WF_WCF_Samples\WCF\Basic in the examples you can find many Service/Client setups that you should go through first. MSDN Magazine has tons of articles on this topic.
In a 10,000 foot view of things:
Client - To consume service create a test console application. Add Service Reference in your project (when you right click references you will see that option). Point the address of the Service Reference dialog to the service you would like to consume and lot of stuff will happen. Final result is that you can call service methods on your service with something like below (where Service1 will be replaced with what ever service you are calling)
static void Main(string[] args)
{
var proxy = new ServiceReference1.Service1Client();
var test = proxy.GetData(1);
}
Service - you would create an interface with methods and types then decorate this interface with attributes for example:
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
These are operations (OperationContract) that your serive can perform. Service methods can return primitive or complex type (string vs. CompositeType) as well as take parameters that are complex or primitive.
You would implement this contract:
public class Service1 : IService1
{
public string GetData(int value)
{
throw new ApplicationException("Boom");
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;
}
}
Next you need to host your service. You have many options to accomplish this depending on your hosting requirements. The simplest hosting you can do is using Console application:
class Program
{
static void Main(string[] args)
{
var host = new ServiceHost(typeof(Service1), new Uri("http://localhost:8999/"));
host.AddServiceEndpoint(typeof(IService1), new BasicHttpBinding(), "");
var metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metadataBehavior == null)
{
metadataBehavior = new ServiceMetadataBehavior();
metadataBehavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(metadataBehavior);
}
host.Open();
Console.WriteLine("Running..");
Console.ReadLine();
}
}

wcf service stop responding i think it because the application is not closing connactions to wcf

this is not my wcf service but i would like to fix it
i need second opinion
here is the code of opening the service from silverlight
i can not put all the code because the project is very big
i just do not see in all the project a m_MdxService.close()
and i think problem off randomly the wcf stop responding
and the only thing fixing it is recycling appication pool
is because the silverlight is not closing the wcf object .
the wcf service is running on it own application pool . the server is 64 bit
public abstract class CubeControl : Control, IFilter
{
protected MdxClient m_MdxService;
protected GeneralClient m_GeneralService;
protected PortalClient m_PortalService;
protected ListsSoapClient m_PortalListsService;
public GraphControl(string cubeName, SharedContract.Filters filter)
: base(cubeName)
{
AttachEvents();
Init(filter);
}
public override void UpdateGraph()
{
flipable.Visibility = Visibility.Collapsed;
progressStackPanel.Visibility = Visibility.Visible;
noDataStackPanel.Visibility = Visibility.Collapsed;
DataPointEventArgs dpe;
switch (m_DrillLevel)
{
case 0:
m_MdxService.GetGraphDataAsync(SharedContract.Enums.Query.NumberOfEmployees, Filter, null, null);
break;
case 1:
dpe = m_DrillParam as DataPointEventArgs;
m_MdxService.GetGraphDataAsync(SharedContract.Enums.Query.NumberOfEmployeesYears, Filter, dpe.Key, null);
break;
case 2:
dpe = m_DrillParam as DataPointEventArgs;
string temp = selectedYear + "," + dpe.Key.ToString();
m_MdxService.GetGraphDataAsync(SharedContract.Enums.Query.NumberOfEmployeesMonth, Filter, temp, null);
break;
}
}
void InitServices()
{
m_MdxService = new MdxClient();
m_MdxService.InnerChannel.OperationTimeout = new TimeSpan(0, 4, 0);
m_GeneralService = new GeneralClient();
m_GeneralService.InnerChannel.OperationTimeout = new TimeSpan(0, 4, 0);
m_PortalService = new PortalClient();
m_PortalService.InnerChannel.OperationTimeout = new TimeSpan(0, 4, 0);
m_PortalListsService = new ListsSoapClient();
m_PortalListsService.InnerChannel.OperationTimeout = new TimeSpan(0, 4, 0);
}
void AttachEvents()
{
m_MdxService.GetGraphDataCompleted += new EventHandler<GetGraphDataCompletedEventArgs>(m_MdxService_GetGraphDataCompleted);
}
void m_MdxService_GetGraphDataCompleted(object sender, GetGraphDataCompletedEventArgs e)
{
GetGraphDataCompleted(sender, e);
GetDataCompleted(this);
}
}
Instead of creating the client withing the control why not have a central access and creating point for the service proxy withing your silverlight client.
Eg. On the application class of your silverlight app add a member MdxService of type "proxy". Then at application startup time configure the binding and endpoint and create the instance.
Then within your control access it using App.Current.MdxService.GetGraphDataAsync also register for the completed event with App.Current.MdxService..GetGraphDataCompleted.
That way you have one instance of your service client.
I do however think that your issue runs deeper and you need to find the root cause.If the application pool needs recycling there definitely some other cause in my mind. Have a look at the size of your workingset on the server hosting the service. It might be that api has causing memory issues. If its around 900MB and appPool is running in 32bit mode you have a problem on server if 64bit mode it will be able to handle much more tho.
maybe think about running that service separately. In its own application pool and compile and deploy it separately.
Hope helps
Cheers

System.ServiceModel.ClientBase connected to Service

I have the following code:
public partial class MyServiceClient : System.ServiceModel.ClientBase<...
if (m_MyClient == null)
m_MyClient = new MyServiceClient
("BasicHttpBinding_IMyService", remoteAddress);
WriteOutput("Successfully connected to service");
My question is how do i know that my client actually connected to the service at this point? I would like to display a message of either failure or success.
When you've created the client, and no exception like EndpointNotFoundException has occured - then you are "connected" to the service which really means: the communication channel between the client and the service is ready to be used for sending messages back and forth. That's all there is - there's nothing on the server side yet to really handle your calls (except for the channel listener which will get activated if a message arrives).
You can also check the client channel's .State property - ideally, it should be Opened at that point:
Use this if you're deriving from ClientBase<T>
m_MyClient.State == CommunicationState.Opened
or this is you're using the standard client class generated by the Add Service Reference functionality in Visual Studio:
(m_MyClient as IClientChannel).State == CommunicationState.Opened
After realizing what i mentioned in my above comment, i realized the answer to my question was as follows:
In my ServiceContract i added the following:
[OperationContract]
bool IsAlive();
Whose implentation simply looks as follows:
public bool IsAlive()
{
return true;
}
Then changed my code as follows:
m_MyClient = new MyServiceClient("BasicHttpBinding_IMyService", remoteAddress);
try
{
m_MyClient.IsAlive();
}
catch (EndpointNotFoundException)
{
WriteOutput("Unable to connect to service");
m_MyClient = null;
}
if (m_MyClient != null)
WriteOutput("Successfully connected to service");

How to implement IsOneWay=true in WCF nettcpBinding

How can I implement one way WCF operations?
I just tried using IsOneWay attribute as:
[OperationContract(IsOneWay=true)]
void MethodName(string param1, int param2)
Is there any other change I need to make or any specific change in app.config?
FYI, my WCF service implements netTcpBinding, though I think that shouldn't make any difference.
As shown, your code looks ok. There should be no problem with doing one-way calls with netTcpBinding.
If you're interested, chapter 5 in Juval Lowy's awesome Programming WCF Services 2nd Edition contains a good bit of information about one-way services.
From what you've shown, so far though I don't see anything wrong. Please give us some more details.
We had a problem with one-way calls not returning immediately using the NetTcpBinding. This blog post identifies the problem and provides a solution.
http://blogs.msdn.com/b/distributedservices/archive/2009/02/12/client-proxy-close-method-call-does-not-finish-immediately-in-one-way-wcf-calls.aspx
From the article:
Problem: Clients calling a one-way method in WCF Service and then close method on proxy does not return until the call is actually finished or call times out. Ever wonder why this happens?
Cause: When you specify “One-Way” on your interface, the underlying channel operation is still two-way since the one way binding element is not in the channel stack. Thus, the close operation gets blocked until the one way operation completes.
This is by design and the development team is working to change it in future versions of .Net framework.
...
Solution (Work around):
Layer the OneWayBindingElement on top of netTcpBinding as shown in the below code. This way, close call on proxy will return immediately and eventually the one-way call will return in fire and forget fashion.
[ServiceContract]
public interface IService1
{
[OperationContract(IsOneWay = true)]
void SetData(int value);
}
public class Service1 : IService1
{
public void SetData(int value)
{
//Application specific code
}
}
Service Host code:
Form1ServiceHost = new ServiceHost(this, new Uri("net.tcp://localhost:8091/WindowsFormApp/Form1/"), new Uri("http://localhost:8090/WindowsFormApp/Form1/"));
Binding binding = new NetTcpBinding();
BindingElementCollection oldBindingElements = binding.CreateBindingElements();
BindingElementCollection bindingElements = new BindingElementCollection();
bindingElements.Add(new OneWayBindingElement());
foreach (BindingElement bindingElement in oldBindingElements)
{
bindingElements.Add(bindingElement);
}
binding = new CustomBinding(bindingElements);
Form1ServiceHost.AddServiceEndpoint("WCFServiceLibrary.IService1", binding, "");
Form1ServiceHost.Open();
Client Code:
Binding binding = new NetTcpBinding();
BindingElementCollection oldBindingElements = binding.CreateBindingElements();
BindingElementCollection bindingElements = new BindingElementCollection();
bindingElements.Add(new OneWayBindingElement());
foreach (BindingElement bindingElement in oldBindingElements)
{
bindingElements.Add(bindingElement);
}
binding = new CustomBinding(bindingElements);
Service1Client client = new Service1Client(binding, new EndpointAddress("net.tcp://localhost:8091/WindowsFormApp/Form1/"));
client.SetData(10);
Console.WriteLine("set data");
Console.WriteLine("Now closing the channel,Before close, current time is {0}", DateTime.Now.ToString() + " " + DateTime.Now.Millisecond.ToString());
client.Close();
Console.WriteLine("Now closing the channel,After close, current time is {0}", DateTime.Now.ToString() + " " + DateTime.Now.Millisecond.ToString());`