Web Service returning object with null fields - c#

Never seen this one before.
WebService.Implementation imp = new WebService.Implementation();
WebService.ImplementationRequest req = new WebService.ImplementationRequest();
return imp.GetValue(req);
The object that imp returns is not null. It's returning an ImplementationResponse, as expected. But all of the fields in that object are null. Which is not expected. The WebService, currently, just returns some constant dummy data. We've tested this on another developer's machine, works just fine.
I suppose I should also note that the WebService should throw an exception if I pass null into the GetValue method. It doesn't. Not for me.
Any idea what could be wrong with my environment that could make a WebService return an object, but make every value in that object null? And somehow 'magically' return this mystery object when it should be throwing an exception?

That usually happens when there's a discrepancy between the generated code and the xml being returned by the web service so it cannot be deserialized.
Grab the wsdl again, regenerate all the proxy classes and try again. Make sure you are sending the correct dummy data.
Update:
This used to happen to me a lot because the web services weren't managed by my team and we wouldn't get any notice of changes made to the service. We ended up intercepting the soap messages in the web service pipeline for debugging. Here's a great resource to get you on your way.
You don't need to change anything in the pipeline, just grab the soap messages and save them so you have debug later. Most of the times it turned out to be just that, a change in the contract. Other times we wouldn't have a contract so there was no way of knowing of changes without catching the envelopes.
Anyway, even if it's not your problem I think it's a good thing to have.

Are the fields marked with < DataMember()> attributes as they won't serialize otherwise?
<DataMember()> _
Public Property SomeField() As String
Get
Return m_strSomeField
End Get
Private Set(ByVal value As String)
m_strSomeField= value
End Set
End Property
Also, consider using trace viewer to analyse the messages sent between the client and server. For info see:
https://stackoverflow.com/questions/560370/handling-wcf-proxy-null-return-issue

I suppose I should also note that the
WebService should throw an exception
if I pass null into the GetValue
method
You didn't pass null here,you passed in a request object.
Also, you need be able to debug into the web service to see what's going on there. I assume you are implementing this internally, since you can set it to constant dummy value.

Related

Application fails when trying to read data with debugger

I have a hierarchical model of five object levels. So each object level contains a list of sub-level objects. when I seat a break point and step over with debugger to read the data from the last level object, I get question marks for each property value and the application instantly closes (doesn't crash). If I try to use these property values somewhere else in the application, then I get the stack overflow exception. So these data definitely can't accessed, but I just don't know why. Has anyone had similar problem?
I had a similar problem once.
It was the object ToString() method raising an exception trying to access a null value and making everything crash.
With so little information it's actually hard to tell, just look if it's also your case

WCF Service FaultContract Understanding

I have a WCF service and I have a FaultContract. I have a Reason in the FaultContract so I have something like this.
FltInfo.Reason = "This is a test";
throw new FaultException<FaultInfo>(FltInfo, new FaultReason(FltInfo.Reason));
Obviously, you see I have the FaultInfo class defined for my data contract. But what would I need to do or how would I do it if I want to get like the fault code, details, or a level (criticality type) aspect with it?
If I didn't include some of those would I still get a soap fault message?
Also, wouldn't the triggering of the faultexception from a TRY-CATCH (or what have you) terminate the communication in the send/receive aspect? Meaning if I have 1 message coming through the receive and that 1 message has a list of let's say 100 items (an array for instance), if I am processing through the array of 100 and I get to let's say the 30th item but it triggers the fault. Would I not lose everything (all 100) because a response was never done and only a fault?
Thanks
You can add the fault code,et using the various constructors of fault exception. And yes, if you leave them blank, you will get WCF default values. You are additionally correct that if you throw a fault exception when processing a single item in the list you will break out of the normal path and will return just your fault.
You can modify this by including your response type in part of the fault and some how marking a single part as invalid. Or your service can have a wrapper response type that allows you to mark specific parts of the data returned as invalid it it makes since to do so in your solution.

Does throwing exception at the end of constructor damage the object?

I'm working on a software communicating with external device. The device requires a set of initialization values (calibrationData). Those calibration data differ from piece to piece of this equipment. In first versions the calibrationData can be selected by user and thus the user may by accident load calibrationData obtained on different piece. The device would work, but will measure incorrectly.
I have
public Instrument(CalibrationData calibration)
{
_camera = new Camera();
_driver = new Driver();
if (_camera.GetUniqueId() != calibration.GetCameraUniqueId())
throw new WrongCalibrationException("Calibration file was obtained on different equipment.");
//Don't write anything here. Exception has to be the last code in the constructor.
}
and then somewhere else
try
{
instrument = new Instrument(calibration);
}
catch (WrongCalibrationException e)
{
MessageBox.Show("You tried to load calibration obtained on different device.");
}
I'm not able to check the ID before I'm connected to the device.
This question comprises out of two in fact.
Is my solution correct? I want to test usage of proper calibration automatically and not rely on the programmer using use my code to call another method (Something like Instrument.AreYouProperlyCalibrated())
Is the object constructed properly when the exception is thrown at the end of constructor? I'm a bit afraid that C# is doing some mumbo jumbo after the construcor finishes and that this might be different in case the ctor threw an exception.
Thanks
The instance already fully exists before the constructor begins (indeed, you can even completely bypass all constructors and still get a valid instance) - it just means that any initialization code that didn't execute won't have executed.
For example, while it isn't a good idea, you can pass the object instance out of the type during the constructor, i.e.
_camera.HereIsMe(this);
or
SomeExternalObject.Track(this);
so nothing too terrible will happen, since as far as the runtime is concerned this object exists like normal, and must be handled properly. However, in some cases it is cleaner to use a factory:
public static YourType Create(args) {
// TODO: perform enough work to validate
return new YourType(validated args);
}
But to reiterate; if there is a problem, then throwing from the constructor is not unexpected and is not harmful.
It's a matter of preference. For example, DateTime throws an exception in its constructor. If you'd rather not, you could use a static method like Build(Calibration calibration). A good practice is to use XML comments to let users of your type know that the constructor throws an exception in an <exception> tag.
You can throw exceptions from wherever you want in your code.
If your constructor has a throw somewhere, and that throw occurs, the object won't be created or, to be more correct, it will be created but your code execution flow will follow the exception, so you won't be in the code branch where the object was being created, so it's like it was not created at all for what concerns you.
So I'd say your approach, considering only the code you posted, is ok. Obviously there could be other problems related to things that could be in the Camera and Driver constructors (stuff not disposed, etc) but that's another matter.
it's a contentious subject, but at the end of the day it is perfectly valid to throw exceptions in constructors. here are some links that discuss and validate the practice:
Throwing ArgumentNullException in constructor?
http://bytes.com/topic/c-sharp/answers/518251-throwing-exception-constructor
http://blog.aggregatedintelligence.com/2009/04/can-constructors-throw-exceptions.html
I would like to add to Marc's answer by pointing out that the Camera and Driver objects should be getting injected into the class. See this (one of MANY) article(s) on implementing Dependency Injection in C#
Hopefully I won't get flogged for this being an opinion. ;)

Proper error handling in ASP.NET MVC2

I have an override OnException(ExceptionContext filterContext) in my base controller to catch the app during any errors, and then log them. The problem I'm getting in my app is this particular method is fired off four times for certain errors. I'll walk you through a scenario:
Let's say i navigate to:
http://localhost:180/someController/someAction?someId=XX
And I have poor object handling in my code. The Id passed in is an invalid one, and it retrieves some null object, I then, bc of my bad object handling, try to operate on a null object. I get an exception.
BaseController's OnException is fired off here.
That null object is still returned out to the view, where the view tries to bind it to something, or what have you.
BaseController's OnException is fired off here again, for the error in the view.
Essentially, only one error is important to me, but the trickle up effect is causing more errors to fire off, and spam my inbox :-/.
What is the correct way to catch an error in MVC2 and not have this happen to me?
I would recommend you inheriting from the HandleError attribute and rolling your exception handling in there. Overriding the OnException on a single controller means you either have a lot of exception handling code in a lot of controllers or your inherit from a base one, which due to the MVC pipeline is not really necessary in either case.
By using the attribute, you should have one occurrence of an error per action executed, and once the error is handled it won't fire again. Hopefully this will cut down on repeat exception messages.
I personally use attributes for the exception handling cause it's cleaner and more reusable and get's rid of a lot of noise within my actions.
First to explain why you are getting multiple errors. First error will be from trying to operate on a null object most likely in your model or controller. Your then probably getting a 2nd exception when the view is trying to bind to a null object when it is expecting an object to exist. Not exactly sure why you are getting 4 errors but could be because the code is trying to operate on an object that is currently null.
My first suggestion would be have your OnException code redirect the application to a friendly error page. Your probably just eating up each new exception and not letting the web.config handle the error pages properly if you have that setup to display an error page.
My second suggestion would be to add some code to check for null objects before you operate on them. These are commonly called Guard Clauses, and are very helpful and useful to implement. You can then determine a nice friendly way to handle errors without always logging an exception if you don't need to and to also display a friendly message to a user besides a generic "An Error has occured." message.
For example in your Controller you could check for a null object and pass an alternate view to the user if that object is null
Function Example As ActionResult
dim obj as Object = GetObject
If obj is Nothing Then
Return View("FriendlyNoObjectView")
Else
Return View(obj)
End If
End Function
I know this is vb (Sorry I know that better then c#) but the idea is the same. If you wanted you could still log that as an error, but you would then prevent the error from happening many times. It's always good practice to handle the error when it occurs and try not to let it float all the way to the top of the stack and cause multiple other errors.
Hope this helps these were just my quick thoughts from reading your question.

web service exception handling

I have a WebMethod that receives following types of parameters:
[WebMethod]
User(long userid,int number)
When Client sends parameter with different types from I want, I have to catch this error and write to database etc.
For example ArgumentExceptions...
How can I solve this?
Thanks.
Have you tried what happens when a client uses the wrong types?
I would expect the SOAP library to trap this and raise an exception.
Inside your own method you can only check the values of the incoming parameters. And that works just like inside a normal (non-web) method.
You can use the following approach:
Each web method will always return some sort of WebMethodResult.
For example
[WebMethod]
public WebMethodResult DoSomethng(guid p_userId)
{
IfMethodIsSuccessful()
{
WebMethodResultSuccess successResult = new WebMethod();
// Add required information into web method result object
return successResult;
}
else
{
WebMethodResultFailure failedResult = new WebMethodResultFailure();
return failedResult;
}
}
Idea here is that whenever web method is called it will return some sort of object.
In this case the WebMethodResult will be the parent class and WebMethodResultSuccess and WebMethodResult failure would inherit from the parent class.
Instead of IsMethodIsSuccessfull you can add your own logic, wrap everything into a try catch block and return success/failure results.
If you call the web methods from the java script or jquery, the exception won't be passed back to the client unless you use SOAP or some sort of alternative. By sending back custom objects, you can read them through javascrip/jquery and display appropriate message to the user.
Hope this makes sense.
In terms of logging, you should probably write a generic exception handling layer or look into open source alternatives.
You woulc catch specific exception and pass it to exception handling layer. Within that layer (dll) you'll log the exception either in the database or write into a flat file. DB is probably a better option since the data can be easily analysed.
Another alternative is to log into windows event log, but I personally don't like this because it's not that easy to produce statistics on the exceptions and I think it has a limit in size.

Categories

Resources