When is the last moment I can return an exception to a client in WCF? - wcf

Let's say I have this in an implementation of IInstanceProvider:
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
try
{
unitOfWork.Commit();
}
catch (Exception)
{
unitOfWork.Rollback();
throw;
}
finally
{
unitOfWork.Dispose();
}
}
That throw; will never be returned to the client because it is being called after the service has done it's work and returned data to the client, and is therefore done. How else can I return the exception? Or is there a better place to do this?

I think you are looking in the wrong place to do this. I think a better choice would be to implement the IDispatchMessageInspector interface and attach it to the collection exposed by the MessageInspectors property on the DispatchRuntime (through a behavior, most likely).
With this, you can inspect messages coming in and going out, and modify them if need be (which is how your exception would be realized, as a fault in the return message). Because of this, you will not just let the exception bubble up, but rather, you would change it to a fault message and set the return message to that.

I'm not as familiar with transactions in WCF as I should be. What in the above code returns the results to the client? Is it the rollback?

Related

Should a class be able to catch an exception from a class that it doesn't know about?

I wrote some code in an MVC Framework that looks something like:
class Controller_Test extends Controller
{
public function action_index()
{
$obj = new MyObject();
$errors = array();
try
{
$results = $obj->doSomething();
}
catch(MyObject_Exception $e)
{
$e->getErrors();
}
catch(Exception $e)
{
$errors[] = $e->getMessage();
}
}
My friend argues that the Controller should know nothing about MyObject, and therefore I should not catch MyObject_Exception.
He argues that the code should do something like this instead:
class Controller_Test extends Controller
{
public function action_index()
{
$obj = new MyObject();
$errors = array();
if($obj->doSomething())
{
$results = $obj->getResults();
}
else
{
$errors = $obj->getErrors();
}
}
I definitely understand his approach, but feel as though state management can lead to unintended side effects.
What is the right or preferred approach?
Edit: mistakenly put $obj->getErrors() in MyObject_Exception catch clause instead of $e->getErrors();
The debate about exceptions vs. returned error codes is a long and bloody one.
His argument breaks down in that, by using a getErrors() function, you are learning information about the object. If that is your reason for using a boolean return to indicate success, then you are wrong. In order for the Controller to handle the error properly, it has to know about the object it was touching and what the specific error was. Was it a network error? Memory error? It has to know in some way or another.
I prefer the exception model because it's cleaner and allows me to handle more errors in a more controlled fashion. It also provides a clear cut way for the data relating to an exception to be passed.
However, I disagree with your use of a function like getErrors(). Any data pertaining to the exception that would help me handle it should be included with the exception. I should not have to go hunting into the object again to get information about what went wrong.
Did the network connection timeout? The exception should contain the host/port it tried to connect to, how long it waited, and any data from the lower networking levels.
Let's do this in example (in psuedo c#):
public class NetworkController {
Socket MySocket = null;
public void EstablishConnection() {
try {
this.MySocket = new Socket("1.1.1.1",90);
this.MySocket.Open();
} catch(SocketTimeoutException ex) {
//Attempt a Single Reconnect
}
catch(InvalidHostNameException ex) {
Log("InvalidHostname");
Exit();
}
}
}
Using his method:
public class NetworkController {
Socket MySocket = null;
public Boolean EstablishConnection() {
this.MySocket = new Socket("1.1.1.1",90);
if(this.MySocket.Open()) {
return true;
} else {
switch(this.MySocket.getError()) {
case "timeout":
// Reattempt
break;
case "badhost":
Log("InvalidHostname");
break;
}
}
}
}
Ultimately, you need to know what happened to the object to know how to respond to it, and there is no sense in using some convoluted if statement set or switch-case to determine that. Use the exceptions and love them.
EDIT: I accidentally the last half of a sentence.
In general, I would say that what's important is whether the controller understands the meaning of the exception and can handle it properly. In many cases (if not most), the controller will not know how to properly handle the exception, and so should not catch and handle it.
On the other hand, the controller might reasonably be permitted to understand some specific exception like a "DatabaseUnavailableException", even if it has no idea how or why MyObject used a database. The controller might be permitted to retry the call to MyObject a certain number of times, all without knowing about how MyObject is implemented.
First of all controller is not meant for handling the underlying exceptions thrown by classes.
Even if one occurs controller should halt saying something wrong at underlying error.
This way we make sure that controller does really and only do the job of flow control.
The other classes which give controller some output should be error free unless the error is very much controller specific.

WP7: Unable to catch FaultException in asynchronous calls to WCF service

I am currently developing a Windows Phone 7 App that calls a WCF web service which I also control. The service offers an operation that returns the current user's account information when given a user's login name and password:
[ServiceContract]
public interface IWindowsPhoneService
{
[OperationContract]
[FaultContract(typeof(AuthenticationFault))]
WsAccountInfo GetAccountInfo(string iamLogin, string password);
}
Of course, there is always the possibility of an authentication failure and I want to convey that information to the WP7 app. I could simply return null in that case, but I would like to convey the reason why the authentication failed (i.e. login unknown, wrong password, account blocked, ...).
This is my implementation of the above operation (for testing purposes, all it does is throwing an exception):
public WsAccountInfo GetAccountInfo(string iamLogin, string password)
{
AuthenticationFault fault = new AuthenticationFault();
throw new FaultException<AuthenticationFault>(fault);
}
Now, if I call this operation in my WP7 app, like this:
Global.Proxy.GetAccountInfoCompleted += new EventHandler<RemoteService.GetAccountInfoCompletedEventArgs>(Proxy_GetAccountInfoCompleted);
Global.Proxy.GetAccountInfoAsync(txbLogin.Text, txbPassword.Password);
void Proxy_GetAccountInfoCompleted(object sender, RemoteService.GetAccountInfoCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
return;
}
}
The debugger breaks in Reference.cs, saying that FaultException'1 was unhandled, here:
public PhoneApp.RemoteService.WsAccountInfo EndGetAccountInfo(System.IAsyncResult result) {
object[] _args = new object[0];
PhoneApp.RemoteService.WsAccountInfo _result = ((PhoneApp.RemoteService.WsAccountInfo)(base.EndInvoke("GetAccountInfo", _args, result)));
return _result;
}
BEGIN UPDATE 1
When pressing F5, the exception bubbles to:
public PhoneApp.RemoteService.WsAccountInfo Result {
get {
base.RaiseExceptionIfNecessary(); // <-- here
return ((PhoneApp.RemoteService.WsAccountInfo)(this.results[0]));
}
}
and then to:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
After that, the app terminates (with or without the debugger).
END UPDATE 1
Now, I would love to catch the exception in my code, but I am never given the chance, since my Completed handler is never reached.
Based on similar questions on this site, I have already tried the following:
Re-add the service reference --> no change
Re-create a really simple WCF service from scratch --> same problem
Start the app without the debugger to keep the app from breaking into the debugger --> well, it doesn't break, but the exception is not caught either, the app simply exits
Tell VS 2010 not to break on FaultExceptions (Debug > Options) --> does not have any effect
wrap every line in my app in try { ... } catch (FaultException) {} or even catch (Exception) --> never called.
BEGIN UPDATE 2
What I actually would like to achieve is one of the following:
ideally, reach GetAccountInfoCompleted(...) and be able to retrieve the exception via the GetAccountInfoCompletedEventArgs.Error property, or
be able to catch the exception via a try/catch clause
END UPDATE 2
I would be grateful for any advice that would help me resolve this issue.
The framework seems to read your WsAccountInfo.Result property.
This rethrows the exception on client side.
But you should be the first to read this property.
I don't know your AuthenticationFault class, does it have a DataContractAttribute and is it a known type like the example in
http://msdn.microsoft.com/en-us/library/system.servicemodel.faultcontractattribute.aspx ?
I believe I had the same problem. I resolved it by extending the proxy class and calling the private Begin.../End... methods within the Client object rather than using the public auto-generated methods on the Client object.
For more details, please see:
http://cbailiss.wordpress.com/2014/02/09/wcf-on-windows-phone-unable-to-catch-faultexception/

Error Handling in WCF Service

With the following service method example:-
[PrincipalPermission(SecurityAction.Demand, Role="BUILTIN\\Administrator")]
public string GetTest()
{
try
{
return "Hello";
}
catch (Exception ex)
{
throw ex;
}
}
How do I get an error from the method when the caller is not in the correct Role. In design time the error breaks on the method line (i.e. public string GetTest) and does not reach the catch. At run time it is reported in my silverlight application as an unhandled error (I have try.. catch blocks there too).
There doesn't seem to be a place to catch the error as it never gets into the try blocks!!
The check for the role is made (by the WCF runtime) before the method is actually called - not inside the method!
You need to handle this exception on the caller's side when you make this call.
If you need to check certain conditions inside your service code, don't decorate the method with an attribute, but instead use the role provider in code to check for a given condition.
If you want global error handler for your WCF service you can implement IErrorHandler and add it in custom behavior. Operation can't catch exceptions thrown outside of its try block.

Multiple Methods to call a WCF Service

I have a class that handles all the interaction in my application with my WCF service and it seems that MSDN say that the use of Using)_ statement with WCF is bad - I can see why this is bad and agree with it (http://msdn.microsoft.com/en-us/library/aa355056.aspx)
my problem is that their suggested method of implementation will mean that i have 10 methods [as 10 public methods in my service] that will have the same structure code and this of course does not follow the DRY principal - the code looks similar to the following:
try
{
results = _client.MethodCall(input parameteres);
_client.Close();
}
catch (CommunicationException)
{
if (_client != null && _client.State != CommunicationState.Closed)
{
_client.Abort();
}
}
catch (TimeoutException)
{
if (_client != null && _client.State != CommunicationState.Closed)
{
_client.Abort();
}
}
catch (Exception ex)
{
if (_client != null && _client.State != CommunicationState.Closed)
{
_client.Abort();
}
throw;
}
This doesn't have any logging yet but of course when I do come to start logging it then I will have to add the logging work in almost 10 different places
does anyone have any tips on how I can be a bit more resourceful here in reusing code
thanks
paul
I would use some general-purpose, configurable exception handling component that allows basic exception handling processing like logging, re-throwing etc. to be decoupled from the actual place of handling. One example of such a component is Microsoft's Exception Handling Application Block.
Then you could end up with a code like this:
try
{
results = _client.MethodCall(input parameteres);
_client.Close();
}
catch (Exception ex)
{
_client.CloseIfNeeded();
if (!ex.Handle("Wcf.Policy")) throw;
}
where CloseIfNeeded denotes a custom extension method encapsulating the WCF channel closing logic, and the Handle exception method calls the exception handling mechanism, passing in a name of the exception policy that shall be applied on this place.
In most cases, you can reduce exception handling logic to a decent one or two lines of code, giving you several benefits:
instant configurability of exception handling behavior (policies)
extensibility with custom exception handlers bound to specific types of exceptions and exception policies
better manageability and readability of code

Serializing Linq2Sql over Wcf - bug or misunderstanding?

Working with Linq2Sql as a driver for a Wcf Service. Lets go bottom up....
Down at the bottom, we have the method that hits Linq2Sql...
public virtual void UpdateCmsDealer(CmsDealer currentCmsDealer)
{
this.Context.CmsDealers.Attach(currentCmsDealer,
this.ChangeSet.GetOriginal(currentCmsDealer));
}
That gets used by my Wcf service as such...
public bool UpdateDealer(CmsDealer dealer)
{
try
{
domainservice.UpdateCmsDealer(dealer);
return true;
}
catch
{
return false;
}
}
And called from my Wpf client code thus (pseudocode below)...
[...pull the coreDealer object from Wcf, it is a CmsDealer...]
[...update the coreDealer object with new data, not touchign the relation fields...]
try
{
contextCore.UpdateDealer(coreDealer);
}
catch (Exception ex)
{
[...handle the error...]
}
Now, the CmsDealer type has >1< foriegn key relationship, it uses a "StateId" field to link to a CmsItemStates table. So yes, in the above coreDealer.StateId is filled, and I can access data on coreDealer.CmsItemState.Title does show me the tile of the appropriate state.
Now, here is the thing... if you comment out the line...
domainservice.UpdateCmsDealer(dealer);
In the Wcf service it STILL bombs with the exception below, which indicates to me that it isn't really a Linq2Sql problem but rather a Linq2Sql over Wcf issue.
"System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException was unhandled by user code
Message="Operation is not valid due to the current state of the object."
InnerException is NULL. The end result of it all when it bubles up to the error handler (the Catch ex bloc) the exception message will complain about the deserializer. When I can snatch a debug, the actual code throwing the error is this snippit from the CmsDealer model code built by Linq2Sql.
[Column(Storage="_StateId", DbType="UniqueIdentifier NOT NULL")]
public System.Guid StateId
{
get
{
return this._StateId;
}
set
{
if ((this._StateId != value))
{
if (this._CmsItemState.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnStateIdChanging(value);
this.SendPropertyChanging();
this._StateId = value;
this.SendPropertyChanged("StateId");
this.OnStateIdChanged();
}
}
}
In short, it would appear that some stuff is happening "under the covers" which is fine but the documentation is nonexistent. Hell googleing for "ForeignKeyReferenceAlreadyHasValueException" turns up almost nothing :)
I would prefer to continue working with the Linq2Sql objects directly over Wcf. I could, if needed, create a flat proxy class that had no association, ship it up the wire to Wcf then use it as a data source for a server side update... but that seems like a lot of effort when clearly this is an intended scenario... right?
Thanks!
The default serializer will first set the State, which will set the StateId. After that it will try to set the serialized StateId and then the exception is thrown.
The problem is that you did not specify that you want you classes to be decorated with the DataContract attribute.
Go to the properties of your LinqToSqlGenerator and set the Serialization Mode to Unidirectional
This will cause the tool to add the DataMember attribute to the required properties and you will see that the StateId will not be a DataMember since it will be automatically set when the State Property is set while deserializing.
The error is likely due to something changing the fk value after it has been initially set - are you sure you don't have some custom initialisation code somewhere that might be initially setting the value?
You could breakpoint the set (where it's throwing), and step out each time it's set (skipping the exception if you need to) which should hopefully point you in the right direction.