How to manually create wcf service fault exception? - wcf

I want to manually make the wcf service channel to enter to faulted state to test a singleton object. I tried many solutions like changing 1. consuming incorrect service host name,
2. Incorrect host ip,
3. reducing exeution time to trigger timeout exception,
4.divide by zero exception, 5.throwing fault exception,
6.null reference exception
But nothing make the service channel faulted. Kindly advice.
Thanks in advance

what type of binding you are using? I think you need to use binding which support session. have you tried using WsHttpBinding?
Please have a look at the code sample below and try to pass 0 value for b to generate DivideByZeroException. This will cause the channel to be in fault state
My service contract:
`
[ServiceContract]
public interface ITestService
{
[OperationContract]
int Division(int a, int b);
}
`
My Service Contract implementation:
`
public class TestService : ITestService
{
public int Division(int a, int b)
{
return a / b;
}
}
`
EndPoint:
`<endpoint address="TestService" binding="wsHttpBinding"
contract="ServiceFaultExceptionTest.ITestService">
</endpoint>
`

Related

c# wcf service how to consume call java client

../Iservice1.cs/
public interface IService1
{
[OperationContract]
Int32 Add(Int32 Num1, Int32 Num2);
}
../Iservice1.svc.cs/
public class Service1 : IService1
{
public Int32 Add(Int32 Num1, Int32 Num2)
{
return Num1 + Num2;
}
}
I created the service. I opened a project in Javada and added the service. But how can I call the service in java "add" method.?
SOLVE:
public class JavaApplication {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
MathService service = new MathService();
IMathService serv;
serv = service.getBasicHttpBindingIMathService();
int x=8, y=2;
int ans;
ans=serv.add(x, y);
System.out.println(ans);
// TODO code application logic here
}
}
Take the IntelliJ IDEA as an example.
In Java, there is a webservice client library. It could help us generate the client java code, then we use the client to call the service.
It prompts us to input the WSDL page when the project is opened, WCF usually publish the complete WSDL file by SingleWSDL instead of WSDL page. The SingleWSDL contains all service definitions in one file. Here we input SingleWSDL URL.
We could also take advantage of Tools Menu to add the Webservice client java code.
The ServiceLocator class includes our client java code. We can use automatically generated HelloWolrdClient.java to simulate the invocation, Press Alt+enter to import the jar package.
At last, please do not forget to modify the service URL, the default is localhost.
Run the Main method in HelloWorldClient. Result.
Feel free to let me know if there is anything I can help with.

One-Way Operations in WCF Services

i am new in wcf. so often read basic tutorial & guide line from many site on wcf. i saw people design their wcf service with special attribute like [OperationContract(IsOneWay=true)]
[ServiceContract]
public interface IArticleService
{
[OperationContract(IsOneWay=true)]
void OneWayMethod();
}
after reading on this one-way operation i understand what it is as follow....
When an operation has no return value, and the client does not care about the success or failure of the invocation. WCF offers one-way operations to support this sort of fire-and-forget invocation,: once the client issues the call, WCF generates a request message, but no correlated reply message will ever return to the client
i like to know if i do not specify IsOneWay=true or IsOneWay=false then IsOneWay=true is default. just tell me what happen when we do not specify this attribute IsOneWay=true ?
or specify like IsOneWay=false
thanks
UPDATE
i read a write up from this url http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.isoneway%28v=vs.110%29.aspx and understand what is the meaning of IsOneWay=true or IsOneWay=false
[ServiceContract]
public class OneAndTwoWay
{
// The client waits until a response message appears.
[OperationContract]
public int MethodOne (int x, out int y)
{
y = 34;
return 0;
}
// The client waits until an empty response message appears.
[OperationContract]
public void MethodTwo (int x)
{
return;
}
// The client returns as soon as an outbound message
// is queued for dispatch to the service; no response
// message is generated or sent.
[OperationContract(IsOneWay=true)]
public void MethodThree (int x)
{
return;
}
}
IsOneway is false by default and you have to explicitly set it to true if you want your operation to be a one way
Check this out :
http://msdn.microsoft.com/en-us/library/ms733035(v=vs.110).aspx

test if jms listener is working

i want to test if the JMS listener is working !
to do that i want to test if the Queue size do not change for more than 5 seconds that means that the listener is not working
what should i add to my code please
try {
if ((msgIdMap.contains(tm.getJMSMessageID())) || !(message instanceof TextMessage)) {
System.out.println("\tListener not working !");
} else {
process((TextMessage) message);
}
If the listener is designed, coded and configured correctly it should be working unless there's a problem with the provider. If there is a problem with the provider, the client portion of the provider should detect it and call your ExceptionListener, if it is defined.
So, I would provide an ExceptionListener, by having your class implement the ExceptionListener:
public class MyJMSClass implements javax.jms.ExceptionListener {
then set the listener on the connection to this class:
connection.setExceptionListener(this);
then provide the recovery code:
public void onException(JMSException jmse) {
log.error("JMS exception has occured.. ", jmse);
// handle exception appropriately, perhaps by attempting to reconnect
}

WCF Service and best practices surrounding clients and open/close methods

Having a WCF service and a Consumer I'm not really sure how to handle the Open and Close methods and the lifetime of my Client.
I created the client myself extending and implementing ClientBase and IMyService. Let's call it MyServiceClient
One place I use it for example is MembershipProvider. So I gave MembershipProvider a MyClient as member variable.
I would like to have it instanced once in the MembershipProvider (via IoC container) and then perhaps do a Open and Close call inside every method call in the client.
public bool ValidateUser(string username, string password)
{
this.Open();
bool b = Channel.ValidateUser(username, password);
this.Close();
return b;
}
Is this the right way to go about it. I don't really understand what's really happening when open/close is called and how having one instance of client affects the service (if at all).
One of the problems with using a single client (WCF proxy) instance is that when a fault occurs the proxy enters a faulted state, and it cannot be reused or Dispose-d, only Abort-ed and created anew. On the other hand, if you use/require Sessions on the service side you need the same proxy instance across multiple calls.
In any case, if you would like to use proxy now and worry about transport, sessions or faults later I suggest a wrapper like this that I use for my WCF proxies:
TResult ExecuteServiceMethod<TResult>(Func<MyService, TResult> method)
{
var proxy = new MyService(); //...Or reuse an existing if not faulted
try
{
return method(proxy);
}
catch(Exception e)
{
//...Handle exceptions
}
finally
{
//...Per-call cleanup, for example proxy.Abort() if faulted...
}
}
and you call your service methods like this:
var result = ExecuteServiceMethod((MyService s) => s.VerifyUser(username, password));
Replace MyService with your actual client type. This way you can later change your opening/closing/reusing strategy, add logging, etc. for all service calls by adding code before or after the line return method(client).

WCF Callback channel faulted

I'm trying to implement a reconnect logic for a wcf client. I'm aware that you have to create a new channel after the current channel entered the faulted state. I did this in a channel faulted event handler:
internal class ServiceClient : DuplexClientBase, IServiceClient
{
public ServiceClient(ICallback callback, EndpointAddress serviceAddress)
: base(callback, MyUtility.GetServiceBinding("NetTcpBinding"), serviceAddress)
{
// Open the connection.
Open();
}
public void Register(string clientName)
{
// register to service
}
public void DoSomething()
{
// some code
}
}
public class ClientApp
{
private IServiceClient mServiceClient;
private ICallback mCallback;
public ClientApp()
{
mServiceClient = new ServiceClient( mCallback, new EndpointAddress("someAddress"));
mServiceClient.Register();
// register faulted event for the service client
((ICommunicationObject)mServiceClient).Faulted += new EventHandler(ServiceClient_Faulted);
}
void ServiceClient_Faulted(object sender, EventArgs e)
{
// Create new Service Client.
mServiceClient = new ServiceClient( mCallback, new EndpointAddress("someAddress"));
// Register the EI at Cell Controller
mServiceClient.Register();
}
public void DoSomething()
{
mServiceClient.DoSomething();
}
}
But in my unit test I still get a "The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state" exception.
Is it possible that the callback channel is still faulted and if yes how can I replace the callback channel?
so far I have experienced that a WCF connection needs to be recreated on fault - there doesn't seem to be a way to recover it otherwise. As for when a fault occurs, the method seems to fire fine, but often it fires and cleans up the WCF connection (establishing a new one, etc) as the current request is going through - causing this to fail - especially true on timeouts.
A couple of suggestions:
- If it is timeout related, keep track of the last time a call was made and a constant containing the timeout value. If the WCF connection will have been dropped due to inactivity, drop it and recreate it before you send the request over the wire.
- The other thing, it looks like you are not re-adding the fault handler, which means the first fault will get handled, but the second time it faults it will fall over without a handler cause no new one has been attached.
Hope this helps
Have you tried to reset the communications channel by calling mServiceClient.Abort in the Faulted event handler?
Edit:
I see that you do not reinitialize the mCallback object in your recovery code. You may need to assign it to a new instance.