Deserialising XML To DTOs In Service Reference - c#

I want to use captured SOAP responses as test data. I've successfully got the SOAP XML and now want to use it to populate the DTOs in my project service reference. This is where I'm coming unstuck.
When I use Message.CreateMessage in conjunction with either message.GetBody or TypedMessageConverter, I have a problem where the deserialiser is trying to populate the PropertyChanged event handler and throws an exception. Why would it do this and how can I stop it?
Added From Comments
Truncated XML:
<GetServiceDetailsResponse xmlns="http://thing.com/thing/">
<GetServiceDetailsResult xmlns:lt4="http://thing.com/thing/types">
<lt4:generatedAt>2016-10-14T14:10:39.7718069+01:00</lt4:gene‌​ratedAt>
</GetServiceDetailsResult>
</GetServiceDetailsResponse>
Code:
string action = null;
XmlReader bodyReader = XmlReader.Create(new StringReader(Resources.eg_xml));
Message msg = Message.CreateMessage(MessageVersion.Default, action, bodyReader);
var b = msg.GetBody<GetServiceDetailsResponse>();`
Exeption
SetUp : System.TypeInitializationException : The type initializer for
'IntegrationTests.GetServiceDetail.Class1' threw an exception. ---->
System.ServiceModel.Dispatcher.NetDispatcherFaultException : The
formatter threw an exception while trying to deserialize the message:
There was an error while trying to deserialize parameter
http://thing.com/thing/:GetServiceDetailsResult. The InnerException
message was ''EndElement' 'GetServiceDetailsResult' from namespace
'http://thing.com/thing/' is not expected. Expecting element
'PropertyChanged'.'

Related

How to Capture Errors When Using Restsharp & System.Text.Json?

I am using RestSharp in my project but when I try to connect to an endpoint. I am getting an error but it is not being captured. The deserialization goes ahead on the object and just returns null instead of throwing an error.
If I was not using deserialization I probably could look at the http status code but that is all hidden.
For instance I have code like ths
var request = new RestRequest("address/update").AddJsonBody(updatedAddress); var response = await client.PostAsync<AddressUpdateResponse>(request);
all I will see in "response" is null. I can't get any other information.
I read this in their error handling section.
WARNING
Please be aware that deserialization failures will only work if the serializer throws an exception when deserializing the response. Many serializers don't throw by default, and just return a null result. RestSharp is unable to figure out why null is returned, so it won't fail in this case. Check the serializer documentation to find out if it can be configured to throw on deserialization error.
I am using System.Text.Json but not sure how to do this.

Using suds for python as a SOAP client and failing to handle NoneType

So i'm using suds-jurko for python3 and I have a value in my request like this:
`Date = None`
Date is not a required field. The issue I'm running into is when it processes the request, I get the error:
WebFault: Server raised fault: 'The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://webservices.soapclient.com/v11:request. The InnerException message was 'There was an error deserializing the object of type WebServices.Posting.Request. The value '' cannot be parsed as the type 'DateTime'.'. Please see InnerException for more details.'
Any clue how I can pass a valid NoneType so that my client won't convert it to an empty string?
If the Date field is optional, you should completely skip it and not try to pass any value at all (even if it's set to NoneType).

JSON.net not finding property value when property exists

I'm working with Json.net, I have retrieved the following JSON from a web page:
"{\"Response\":
[{
\"iconPath\":\"",
\"membershipType\":1,
\"membershipId\":\"124877458474\",
\"displayName\":\"DarylJG\"
}],
\"ErrorCode\":1,
\"ThrottleSeconds\":0,
\"ErrorStatus\":\"Success\",
\"Message\":\"Ok\",
\"MessageData\":{ }}"
Now, I'm getting the following error when trying to return a string from this property:
An unhandled exception of type
'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in
System.Core.dll
Additional information: 'Newtonsoft.Json.Linq.JArray' does not contain
a definition for 'iconPath'
Which the iconPath does exist within this JSON file. The code i'm using:
var response = client.GetAsync("CorrectServerPath & Auth").Result;
var content = response.Content.ReadAsStringAsync().Result;
dynamic item = Newtonsoft.Json.JsonConvert.DeserializeObject(content);
return item.Response.iconPath;
This is the lines of code which are throwing this error, but the following code:
return item.Message;
will return OK
So my overall question, is how can I reach iconPath in the provided json file using JSON.net? As, i'm at a loss. Research material has come up with nothing & Probably using the incorrect Search Terms
Your Response member is an array, not an object. Use item.Response[0].iconPath, instead.

WCF "The given key was not present in the dictionary"

I'm getting this error even though I'm not using a Dictionary, and what's weird is that it's when I call the service.
wsSoapClient client = null;
try
{
client = new wsSoapClient();
}
catch (Exception ex)
{
// - Error in the web.config
}
try
{
SendData sendData = new SendData();
sendData.finishDate = myVar.FinishDate;
sendData.startDate = myVar.StartDate;
// - Other fields
// - This lines throw the error below
ClientResult result = client.FinishCourse(sendData);
}
catch (Exception ex)
{
// - Message: The given key was not present in the dictionary.
}
The stack trace:
StackTrace: at System.Collections.Generic.Dictionary``2.get_Item(TKey key)
at Project.Model.CourseService.FinishCourse(XmlNode node)
The service is up to date, and I couldn't find info on this anywhere else. There's two similar questions on SO but they are about Silverlight and I couldn't figure a relation between this (regular C# WCF calling a service) and the solutions.
What causes this and how do I fix it?
(Edit) More Info: The binding is a basicHttpBinding, http only.
Edit²: The WSDL.
Edit³: Found the issue. Apparently, there was already another error (a value larger than the field allows), the service was returning an error but for some reason, WCF didn't take that as error and didn't threw the exception, and I'm guessing it tried to proceed normally, causing this dictionary error since the XML is not what is was expecting.
Assuming your service method is not the one throwing the exception, then it might be the case with the deserialization of the soap message (i.e request object) that happens on the service side.
Check your code(or wsdl) for SendData and see if there are non nullable properties which you are not setting in the request object i.e. sendData object. Missing required properties might cause issues during deserialization.
Posting the code of SendData and\or FinishCourse service method would be great in analyzing the possible issue.

Unable to send Object while using Web Service

I am trying to send the object through a method api of web service. As service is binded by BasichttpBinding.
OneClickOrder OneClick = new OneClickOrder();
OneClick.Mobile = Session["Mobile"].ToString();
OneClick.OrderDetailsList = OrderDetailsList.ToArray();
OneClick.OrderId = 10000;
OneClick.PromoSiteId = PromoSiteId;
OneClick.TotalPrice = Convert.ToInt32(lblafterDiscount.Text);
var OrderResponse = service.OneClickOrder(OneClick);
While using service API, I got an SOAP exception
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:order. The InnerException message was 'Error in line 1 position 588. 'EndElement' 'order' from namespace 'http://tempuri.org/' is not expected. Expecting element 'Mobile'.'. Please see InnerException for more details.
I didn't get what could be wrong. Is this a problem of Service Side or client side? And i am currently working at client side.
The Problem is that your DataContract class OneClickOrder is not same on both server and client.
At client it is different from Server. So, Check your OneClickOrder DataContract Class, Is both are same on server and client.

Categories